# 124. Binary Tree Maximum Path Sum

{% embed url="<https://leetcode.com/problems/binary-tree-maximum-path-sum/description/>" %}

> time: O(n)

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

```jsx
/**
 * 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;

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/124.-binary-tree-maximum-path-sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
