Description:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
Notes:
- 时间限制:1秒
- 空间限制:32768K
解题思路:前序遍历中的第一个节点就是二叉树的根节点,在中序遍历中,根节点左侧的是其左子树,根节点右侧的是其右子树;根据这个特点我们可以递归构造出一颗二叉树;
Java
/**
* 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) {
return constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
private TreeNode constructBinaryTree(int [] pre, int preSt, int preEd,
int [] in, int inSt, int inEd) {
if (preSt > preEd || inSt > inEd) return null;
TreeNode root = new TreeNode(pre[preSt]);
int pos = inSt;
while (in[pos] != pre[preSt]) pos++;
if (pos > inEd) return root;
root.left = constructBinaryTree(pre, preSt + 1, preSt + pos - inSt,
in, inSt, pos - 1);
root.right = constructBinaryTree(pre, preSt + pos - inSt + 1, preEd,
in, pos + 1, inEd);
return root;
}
}