题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
代码
本题考查递归的思想,首先找到根节点,然后,对子数组调用同一个方法,分别找到左子树的根节点,这样一直往下调用,知道数组为空。
⚠️注意:Arrays.copyOfRange为import java.util.*;中的方法,因此必须引入才能通过。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length==0 || 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));
break;
}
}
return root;
}
}
另一种方法,不需要引入额外包
/**
* 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==null||in==null||pre.length!=in.length||pre.length<1||in.length<1){
return null;
}
return construct(pre,0,pre.length-1,in,0,in.length-1);
}
public TreeNode construct(int[] pre, int ps, int pe, int[] in, int is, int ie) {
if(ps>pe){
return null;
}
int value = pre[ps];//根节点的值
int index = is;
while(index<=ie&&in[index]!=value){
index++;
}
if(index>ie){
throw new RuntimeException("Invalid input");
}
//创建当前的根节点,并为根节点赋值
TreeNode node = new TreeNode(value);
//左子树个数为index-is
//中序遍历左子树范围为:is,index-1,右子树范围为index+1,ie
//前序遍历左子树范围为:ps+1,ps+index-is,右子树范围为:ps+index-is+1,pe
node.left = construct(pre, ps+1, ps+index-is, in, is, index-1);
node.right = construct(pre, ps+index-is+1, pe, in, index+1, ie);
return node;
}
}