106. 从中序与后序遍历序列构造二叉树

题目链接

/**
 * Definition for a binary tree node.
 */
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function(inorder, postorder) {
    // console.log(inorder, postorder);
    if (!inorder.length || !postorder.length) return null;
    if (inorder.length === 1 && postorder.length === 1 && inorder[0] === postorder[0]) {
        return new TreeNode(inorder[0]);
    }
    const curRootVal = postorder.pop();
    const newRoot = new TreeNode(curRootVal);
    // console.log('newRoot', newRoot);
    const splitPos = inorder.findIndex((it)=>it === curRootVal);
    const valListLeft = inorder.slice(0,splitPos);
    const valListRight = inorder.slice(splitPos+1, inorder.length);
    const leftTree = buildTree(valListLeft, postorder.slice(0, valListLeft.length));
    const rightTree = buildTree(valListRight, postorder.slice(valListLeft.length, valListLeft.length + valListRight.length));
    newRoot.left = leftTree;
    newRoot.right = rightTree;
    return newRoot;
};

// 验证代码
(()=>{
    console.log('buildTree', buildTree([9,3,15,20,7], [9,15,7,20,3]));
    console.log('buildTree', buildTree([-1], [-1]));
})();

results matching ""

    No results matching ""