给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
解题思路
如示例1
前序遍历为: [3, 9, 20, 15, 7]
中序遍历为:[9, 3, 15, 20, 7]
我们可以很容易的知道,前序遍历数组的第一个值,就是树的根节点。
在示例中 3 为这颗树的根节点的值, 然后通过这个值去找中序遍历的左右两颗树,
得到中序遍历的左树为 [9] 右树为 [15, 20, 7]。
通过中序遍历左右两颗树的节点数,找到前序遍历的两颗树的值
得到前序遍历的左树为 [9] 右树为 [20, 15, 7]。
一次递归遍历下去,最后返回根节点
代码
var buildTree = function(preorder, inorder) {
// 当前节点不存在时,返回空
if (!preorder.length) return null
// 找中序遍历根节点的位置
let pos = 0;
while(preorder[0] !== inorder[pos]) pos++
// 创建树
let root = new TreeNode(preorder[0])
// 设置树的左右两个节点
root.left = buildTree(preorder.slice(1, pos+1), inorder.slice(0, pos))
root.right = buildTree(preorder.slice(pos+1, preorder.length), inorder.slice(pos+1, preorder.length))
return root
};