需求:
给定节点数为 n 的二叉树的前序遍历和中序遍历结果,请重建出该二叉树并返回它的头结点。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
提示:
- vin.length == pre.length
- pre 和 vin 均无重复元素
- vin出现的元素均出现在 pre里
- 只需要返回根节点,系统会自动输出整颗树做答案对比
数据范围:n \le 2000n≤2000,节点的值 -10000 \le val \le 10000−10000≤val≤10000
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
实现:
- 首先了解前序排列和中序排列的特点,前序排列为根➡左➡右,中序排列为左➡根➡右,即前序排列中第一个节点一定为根节点root 。
- 根据root 的值找到对应中序排列根节点的位置,此节点左侧是左子树,右侧是右子树。
- 进行递归。
- 当子树的序列长度为0时,结束递归,返回null 。
silce(start,end) 方法可从已有的数组中返回选定的元素,可提取字符串的某个部分,并以新的字符串返回被提取的部分。【slice() 方法不会改变原始数组。[start, end) 】
前 序 排 列
中 序 排 列
后 序 排 列
/* 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
}
//找到根节点 root
let root =new TreeNode(pre[0]);
//找到中序遍历对应的跟节点的index
let rootIndex_vin = vin.indexOf(pre[0]);
//左子树递归
root.left = reConstructBinaryTree(pre.slice(1,rootIndex_vin+1),vin.slice(0,rootIndex_vin));
//右子树递归
root.right = reConstructBinaryTree(pre.slice(rootIndex_vin+1),vin.slice(rootIndex_vin+1));
return root
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};
输入:[1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]
返回值:{1,2,3,4,#,5,6,#,7,#,#,8}