题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回 ## 。
解题思路:
题目中给了我们先序遍历和中序遍历;在二叉树的前序遍历中,第一个数字总是树的根结点的值。但在中序遍历序列中,根结点的值在序列的中间,左子树的结点的值位于根结点的值的左边,而右子树的结点的值位于根结点的值的右边。因此我们需要扫描中序遍历序列,才能找到根结点的值。
题目给出的前序遍历序列的第一个数字1就是根结点的值。扫描中序遍历序列,就能确定根结点的值的位置。根据中序遍历的特点,在根结点的值1前面的3个数字都是左子树结点的值,位于1后面的数字都是右子树结点的值。
由于在中序遍历序列中,有3个数字是左子树结点的值,因此左子树总共有3个左子结点。同样,在前序遍历的序列中,根结点后面的3个数字就是3个左子树结点的值,再后面的所有数字都是右子树结点的值。这样就在前序和中序遍历的两个序列中,分别找到了左右子树对应的子序列。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
//重写toString方法
public String toString() {
return "TreeNode [val:" + val +", left:" + left + ", right:" + right + "]";
}
}
class Solution {
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
// 前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
private TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
if (startPre > endPre || startIn > endIn)
return null;
// 前序遍历的第一个数字是根节点的值
TreeNode root = new TreeNode(pre[startPre]);
// 遍历中序数组,找到根节点的位置,创建左右子树
for (int i = startIn; i <= endIn; i++)
if (in[i] == pre[startPre]) {
//左子树
//startPre+1,指的是前序遍历左子树的开始位置,即前序遍历根节点的下一个节点
//startPre+i-startIn是前序遍历左子树结束的位置
//startIn是中序遍历左子树开始的位置;i-1是中序遍历左子树结束的位置
root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1);
//右子树
// 其中(i - startIn)为中序排序中左子树结点的个数
root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn);
break;
}
return root;
}
}
public class TsetDemo {
public static void main(String[] args) {
Solution sol = new Solution();
int[] pre = { 1, 2, 4, 7, 3, 5, 6, 8 };
int[] in = { 4, 7, 2, 1, 5, 3, 8, 6 };
TreeNode result = sol.reConstructBinaryTree(pre, in);
System.out.println(result);
}
}
//运行结果
TreeNode [val:1, left:TreeNode [val:2, left:TreeNode [val:4, left:null, right:TreeNode [val:7, left:null, right:null]], right:null], right:TreeNode [val:3, left:TreeNode [val:5, left:null, right:null], right:TreeNode [val:6, left:TreeNode [val:8, left:null, right:null], right:null]]]