重建二叉树

递归。

 public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
       int m= pre.length;
       int n= vin.length;
       if(m==0||n==0) return null;
       TreeNode root=new TreeNode(pre[0]);
       for (int i=0;i<vin.length;i++){
           if(pre[0]==vin[i]){
               root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(vin,0,i));
               root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(vin,i+1,vin.length));
               break;
           }
       }
       return root;

    }


全部评论

相关推荐

喜欢飞来飞去的雪碧在刷代码:可以试一试字节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务