题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
确定一颗二叉树,需要知道先根遍历和中根遍历序列,或者知道中根遍历和后根遍历序列。每次都由先根遍历序列确定根节点,再在中根遍历序列中确定根节点的位置,将中根遍历序列划分为左右孩子两个中根遍历序列,以此递归调用。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return creatBinaryTree(pre,in,0,0,pre.length);
}
public TreeNode creatBinaryTree(int[] pre,int[] in,int preIndex,int inIndex,int count){
TreeNode root =null;
if(count>0){
int value = pre[preIndex];
int i = 0;
for(;i<count;i++){
if(value == in[i+inIndex])
break;
}
root = new TreeNode(value);
root.left = creatBinaryTree(pre,in,preIndex+1,inIndex,i);
root.right = creatBinaryTree(pre,in,preIndex+i+1,inIndex+i+1,count-i-1);
}
return root;
}
}