1、遍历中序数列,根据前序数列找出左子树和右子树
2、左子树开始执行以上步骤、右子树开始执行以上步骤
代码如下:
public class BTreeSolution {
public TreeNode reConstructBinaryTree(int[] pre,int[] in) {
return reConBTree(pre,0,pre.length-1,in,0,in.length-1);
}
public TreeNode reConBTree(int[] pre,int preLeft,int preRight,int[] in,int inLeft,int inRight) {
if(preLeft > preRight || inLeft > inRight) return null;
TreeNode root = new TreeNode(pre[preLeft]);
for(int i = inLeft ; i < inRight ; i++) {
if(pre[preLeft] == in[i]) {
root.left = reConBTree(pre,preLeft+1,preLeft+i-inLeft,in,inLeft,i-1);
root.right = reConBTree(pre,preLeft+1+i-inLeft,preRight,in,i+1,inRight);
}
}
return root;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {this.val = val;}
}