给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

这个题,学到了一个新知识,前序/后序+中序序列可以唯一确定一棵二叉树

还有一个心得:这种题思路还是尽量往递归,区间分治来靠,野路子通常不太行

以下是我的JS实现

/**
 * 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[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function(preorder, inorder) {
    const map = {};
    for (let i = 0; i < inorder.length; i++) {
        map[inorder[i]] = i;
    }

    const build = (prel, prer, inl, inr) => {
        const val = preorder[prel];
        const node = new TreeNode(val, null, null);
        const valIndex = map[val];
        const leftCount = valIndex - inl;
        const rightCount = inr - valIndex;
        if (leftCount > 0) {
            node.left = build(prel + 1, prel + leftCount, inl, valIndex - 1);
        }
        if (rightCount > 0) {
            node.right = build(prel + 1 + leftCount, prer, valIndex + 1, inr);
        }
        return node;
    };

    return build(0, preorder.length - 1, 0, inorder.length - 1);
};

上一篇 下一篇