题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,2,7,1,5,3,8,6},则重建二叉树并返回。
Solution
先序序列第一个数就是根结点而后是左子树的先序序列和右子树的先序序列,而中序序列是先是左子树的中序序列,然后是根结点,最后是右子树的中序序列。用根结点将中序分出左右子树序列,继而得到先序的左右子树序列,递归重建。
/**
* 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) {
TreeNode root = reBuild(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
public TreeNode reBuild(int[] pre, int startP, int endP, int[] in, int startI, int endI) {
if (startP > endP || startI > endI) return null;
TreeNode root = new TreeNode(pre[startP]);
for (int i = startI; i <= endI; i++)
if (in[i] == pre[startP]) {
root.left = reBuild(pre, startP + 1, startP + i - startI, in, startI, i - 1);
root.right = reBuild(pre, startP + i - startI + 1, endP, in, i + 1, endI);
break;
}
return root;
}
}