Binary Tree Maximum Path Sum

Hard#124tree nodes

You get the root of a binary tree whose values can be negative. A path goes from node to node along the edges, visits each node at most once and has at least one node; it does not have to pass through the root. Find the largest sum of values on a path. Our tree: -5 with children 3 and 6; 3 has children 7 and 9; 9 has a left child -4; 6 has a right child -1. The answer is 19: the path 7 → 3 → 9.

input
root: a binary tree of at least one node, written as on LeetCode: its values level by level, left to right, null for a missing child. Values may be negative.
returns
The largest sum of the values on a path: nodes joined by edges, each node at most once, going up and then down or not passing the root at all. A path has at least one node.
constraints
  • 1 ≤ the number of nodes ≤ 3000
  • −1000 ≤ Node.val ≤ 1000
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * 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 maxPathSum(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.