124. Binary Tree Maximum Path Sum

time: O(n)

space: O(h): average, O(n): worst

/**
 * 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 {TreeNode} root
 * @return {number}
 */

function Memo() {
    this.max;
}

const memo = new Memo();

var maxPathSum = function(root) {
    memo.max = -Infinity;

    findMaxPath(root);
    return memo.max;
};

function findMaxPath(node) {
    if (node === null) return 0;

    const left = findMaxPath(node.left);
    const right = findMaxPath(node.right);
    const curr = node.val;

    // one way
    const localMax = Math.max(curr + left, curr + right, curr);
    // max between left, right, + curr
    memo.max = Math.max(memo.max, localMax, curr + left + right);

    return localMax;

}

Last updated