HardDynamic ProgrammingTreeDepth-First SearchBinary Tree

Binary Tree Maximum Path Sum

LeetCode
1 approach, code in all languages

A path in a binary tree is any sequence of nodes in which each consecutive pair is connected by a parent-child edge. A node may appear in a path at most once, and the path is not required to pass through the root. The path sum is the total of the values of the nodes on that path.

Given the root of a binary tree, return the maximum possible path sum over all paths in the tree. Every tree has at least one node, so at least one path always exists.

Example 1

Input: root = [1,2,3]

Output: 6

The optimal path is 2 -> 1 -> 3 with a sum of 2 + 1 + 3 = 6.

Example 2

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

Output: 42

The optimal path is 15 -> 20 -> 7 with a sum of 15 + 20 + 7 = 42; the negative root is skipped.

Constraints

  • The number of nodes in the tree is in the range [1, 3 * 10^4].
  • -1000 <= Node.val <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now