牛客网上的一道练习题:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
以上就是我们的需求,关于树的相关基础知识请移步本人博客
js高级进阶之数据结构“二叉排序树”的es5和es6实现与应用
链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6?answerType=1&f=discussion
来源:牛客网
1. 分析
根据中序遍历和前序遍历可以确定二叉树,具体过程为:
根据前序序列第一个结点确定根结点
根据根结点在中序序列中的位置分割出左右两个子序列
对左子树和右子树分别递归使用同样的方法继续分解
例如:
前序序列{1,2,4,7,3,5,6,8} = pre
中序序列{4,7,2,1,5,3,8,6} = in
根据当前前序序列的第一个结点确定根结点,为 1
找到 1 在中序遍历序列中的位置,为 in[3]
切割左右子树,则 in[3] 前面的为左子树, in[3] 后面的为右子树
则切割后的左子树前序序列为:{2,4,7},切割后的左子树中序序列为:{4,7,2};切割后的右子树前序序列为:{3,5,6,8},切割后的右子树中序序列为:{5,3,8,6}
对子树分别使用同样的方法分解
2.代码
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
function reConstructBinaryTree(pre, vin) {
if (pre.length == 0 || vin.length == 0) {
return null;
}
pre = Array.from(pre);
vin = Array.from(vin);
let tree = new TreeNode(pre[0]);
let mid = 0;
for (let i = 0; i < vin.length; i++) {
if (vin[i] == pre[0]) {
mid = i;
break;
}
}
tree.left = reConstructBinaryTree(pre.slice(1, mid + 1), vin.slice(0, mid));
tree.right = reConstructBinaryTree(pre.slice(mid + 1, pre.length), vin.slice(mid + 1, vin.length));
return tree;
}
3.测试
let a= [1, 2, 4, 7, 3, 5, 6, 8];
let b = [4,7, 2, 1, 5, 3, 8, 6];
let sd = reConstructBinaryTree(a, b);
console.log(sd);
4.总结
1.通过二叉树的前序和中序遍历生成二叉树最主要是考察前序中序遍历的逻辑关系,前序找到根节点中序找到左右子树。
2.通过递归循环生成每个节点。
3.js数组的slice用法 arr.slice(start,end)生成新的数组及左右子树,对左右子树再次递归直到每个叶子节点