重建二叉树
重建二叉树
http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6
//解题思路: //1、用前序确定root节点 //2、然后在中序中用root节点左右分割,就分辨是左右子树了。 //3、在左右子树中,用递归重复1、2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre == null || pre.length == 0 || in ==null || in.length == 0) { return null; } TreeNode root = new TreeNode(pre[0]); for(int i = 0; i<in.length; i++) { if(pre[0] == in[i]) { root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1 , pre.length), Arrays.copyOfRange(in, i+1, in.length)); } } return root; }