Blind 75
34 / 75Free practice

Binary Tree Maximum Path Sum

Hard · Trees

Jump to code

Find the largest sum along any nonempty path in a binary tree. A path follows parent-child edges without revisiting a node; it need not include the root.

Examples

Example 1

root = [1,2,3]

Output: 6

Example 2

root = [-10,9,20,null,null,15,7]

Output: 42

Constraints

  • 1 <= The number of nodes in the tree <= 1000
  • -1000 <= Node.val <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

A path returned to a parent can use only one downward branch.

Asked in real interviews

Candidates reported versions of Binary Tree Maximum Path Sum from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    3
  ]
]
Expected
6
Case 2
Input
[
  [
    -10,
    9,
    20,
    null,
    null,
    15,
    7
  ]
]
Expected
42
Case 3
Input
[
  [
    -3
  ]
]
Expected
-3
Case 4
Input
[
  [
    2,
    -1
  ]
]
Expected
2
Case 5
Input
[
  [
    1,
    2,
    3,
    4,
    5
  ]
]
Expected
11

Drafts are saved per language in this browser when storage is available.