输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
- 找到根结点,然后分左右,递归。
import java.util.Arrays;
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder){
int n = preorder.length; //前序数组的长度
if (n == 0){
return null;
}
int rootVal = preorder[0];//因为 前序结点顺序是 根 左子树 右子树 所以直接确定根节点
int rootIndex = 0;
for (int i = 0; i < n; i++) { //前序数组和中序数组一样长
if (inorder[i] == rootVal) { //找到中序里面的头结点 分割成 左分支节点和右分支节点
rootIndex = i;
break;
}
}
TreeNode root = new TreeNode(rootVal); // 开始建树 对左右子树递归
root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIndex), Arrays.copyOfRange(inorder, 0, rootIndex));
root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIndex, n), Arrays.copyOfRange(inorder, rootIndex + 1, n));
return root;
}
}