Binary Tree Maximum Path Sum
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,nullfor 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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more depth-first search (dfs) problems
- 104Maximum Depth of Binary TreeEasysolve
- 100Same TreeEasysolve
- 226Invert Binary TreeEasysolve
- 101Symmetric TreeEasysolve
- 112Path SumEasysolve
- 200Number of IslandsMediumsolve
- 695Max Area of IslandMediumsolve
- 133Clone GraphMediumsolve
- 417Pacific Atlantic Water FlowMediumsolve
- 129Sum Root to Leaf NumbersMediumsolve
- 222Count Complete Tree NodesMediumsolve
- 236Lowest Common Ancestor of a Binary TreeMediumsolve
- 130Surrounded RegionsMediumsolve
- 399Evaluate DivisionMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.