难度:中等
题目描述:
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
示例:
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
3
/ \
9 20
/ \
15 7
解题思路:
var buildTree = function(preorder, inorder) {
if (inorder.length === 0) return null;
let root = new TreeNode(preorder[0]);
let index = inorder.indexOf(preorder[0]);
root.left = buildTree(
preorder.slice(1, index + 1),
inorder.slice(0, index)
);
root.right = buildTree(
preorder.slice(index + 1),
inorder.slice(index + 1)
);
return root;
};