給定樹的中序遍歷(左/根/右)和后序遍歷(左/右/根)接谨,構(gòu)造二叉樹祟敛,假設(shè)樹中不存在重復(fù)項(xiàng)兆解。
遞歸實(shí)現(xiàn),faster than 27%
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
var n = inorder.length
if(n === 0 || postorder.length === 0) return null
var val = postorder[postorder.length - 1]
var root = new TreeNode(val)
var index = inorder.indexOf(val)
root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index))
root.right = buildTree(inorder.slice(index + 1),postorder.slice(index, n - 1))
return root
};