描述
给定某二叉树的前序遍历和中序遍历,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
提示:
1.0 <= pre.length <= 2000
2.vin.length == pre.length
3.-10000 <= pre[i], vin[i] <= 10000
4.pre 和 vin 均无重复元素
5.vin出现的元素均出现在 pre里
6.只需要返回根结点,系统会自动输出整颗树做答案对比
示例1
输入: [1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]
返回值: {1,2,3,4,#,5,6,#,7,#,#,8}
说明: 返回根节点,系统会输出整颗二叉树对比结果
示例2
输入: [1],[1]
返回值: {1}
示例3
输入: [1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值: {1,2,5,3,4,6,7}
/* 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 rootValue = pre[0];
const node = new TreeNode(rootValue);
// 寻找中序二叉树中的根节点,此时可以把vin的左边为左子树,右边为右子树
let i = 0;
for(; i < vin.length; ++i){
if(vin[i] === rootValue){
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;
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};