题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
输入:
[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
输出:
{1,2,5,3,4,6,7}
我们先看一个比较简单的二叉树:
该二叉树的前序遍历是:12453,中序遍历是42513。我们知道前序遍历的第一个元素就是根节点。而在中序遍历中位于根节点左边的值就是根节点的左子树部分,右边就是右子树部分。在以上面的例子,中序遍历就被分成了 4 2 5 和 3 两个部分。4 2 5就是左子树,3就是右子树。根据左右子树,继续递归即可得到整棵树。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
// write code here
if (!pre.length || !vin.length) {
return null
}
const rootVal = pre[0];
const node = new TreeNode(rootVal);
let i = 0;
for (; i < vin.length; ++i) {
if (vin[i] === rootVal) {
break;
}
}
node.left = reConstructBinaryTree(pre.slice(1, i + 1), vin.slice(0, i));
node.right = reConstructBinaryTree(pre.slice(i + 1), vin.slice(i + 1));
return node
}