题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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) {
if (pre.length<=0||in.length<=0) {
return null;
}
TreeNode treeNode=new TreeNode(pre[0]);
int rootIndex=0;
for(int i=0;i<in.length;i++){
if(in[i]==pre[0]){
rootIndex=i;
}
}
int []preLeft=new int[rootIndex];
int []preRight=new int[pre.length-rootIndex-1];
int []inLeft=new int[rootIndex];
int []inRight=new int[in.length-rootIndex-1];
for(int i=0;i<rootIndex;i++){
preLeft[i]=pre[i+1];
inLeft[i]=in[i];
}
for(int i=0;i<in.length-rootIndex-1;i++){
preRight[i]=pre[rootIndex+1+i];
inRight[i]=in[rootIndex+1+i];
}
treeNode.left=reConstructBinaryTree(preLeft,inLeft);
treeNode.right= reConstructBinaryTree(preRight,inRight);
return treeNode;
}
}