目录
重建二叉树
描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
示例1
输入:
[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值:
{1,2,5,3,4,6,7}
备注
二叉树数据结构如下:
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){
return null;
}
TreeNode root=new TreeNode(0);
root.val=pre[0];
if (pre.length==1){
return root;
}
int index=findIndex(in,pre[0]);
int leftPre[]=copyArray(pre,1,index+1);
int leftIn[]=copyArray(in,0,index);
int rightPre[]=copyArray(pre,index+1,pre.length);
int rightIn[]=copyArray(in,index+1,in.length);
root.left=reConstructBinaryTree(leftPre,leftIn);
root.right=reConstructBinaryTree(rightPre,rightIn);
return root;
}
public int findIndex(int []arr,int target){
for (int i = 0; i < arr.length; i++) {
if (arr[i]==target){
return i;
}
}
return -1;
}
public int[] copyArray(int []arr,int low,int high){
if (low>=high) return new int[0];
int res[]=new int[high-low];
for (int i = low; i < high; i++) {
res[i-low]=arr[i];
}
return res;
}
}
速度很快,但是占用内存较多