题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

import java.util.*; /**

  • Definition for binary tree

  • public class TreeNode {

  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode(int x) { val = x; }
    
  • } */ //依据题解1写的 public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] vin) { if(pre.length == 0) return null; TreeNode root = new TreeNode(pre[0]);//根节点

     int index = -1;//根节点在中序遍历的位置
     for(int i = 0;i < vin.length;i++) {
     	if(vin[i] == pre[0]) {
     		index = i;
     	}
     }
     
     int[] pre1 = Arrays.copyOfRange(pre, 1, index+1);
     int[] pre2 = Arrays.copyOfRange(pre, index+1, pre.length);
     int[] vin1 = Arrays.copyOfRange(vin, 0, index);
     int[] vin2 = Arrays.copyOfRange(vin, index+1, vin.length);
     
     root.left = reConstructBinaryTree(pre1, vin1);
     root.right = reConstructBinaryTree(pre2, vin2);
     
     return root;
    

    } }

全部评论

相关推荐

axiom15:校友,我感觉你这个简历去华子暑期实习随便去了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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