124. Binary Tree Maximum Path Sum ๐
Last updated
Last updated
Difficulty: Hard
- Tags: Binary Tree
, Dynamic Programming
, Depth-First Search (DFS)
A path in a binary tree is a sequence of nodes where:
Each pair of adjacent nodes in the sequence is connected by an edge.
A node can only appear in the sequence at most once.
The path does not need to pass through the root.
The path sum of a path is the sum of the node values along the path.
Task:
Given the root of a binary tree, return the maximum path sum of any non-empty path.
๐น Example 1:
Input:
Output:
Explanation:
The optimal path is 2 -> 1 -> 3
with a path sum of 2 + 1 + 3 = 6
.
๐น Example 2:
Input:
Output:
Explanation:
The optimal path is 15 -> 20 -> 7
with a path sum of 15 + 20 + 7 = 42
.
The number of nodes in the tree is in the range [1, 30,000]
.
-1000 <= Node.val <= 1000
The solution involves:
Using Depth-First Search (DFS) to explore the tree.
At each node, calculate:
The maximum path sum that can be extended to its parent.
The maximum path sum passing through the current node.
Update the global maximum path sum during the traversal.
DFS Traversal:
Traverse the binary tree using DFS to calculate the maximum path sum at each node.
Maximum Sum at Each Node:
At each node, calculate:
The left subtree sum and right subtree sum, ignoring negative sums (as they reduce the total sum).
The current path sum, which includes the node's value and both left and right subtree sums.
Global Maximum Update:
Update the maxSum
(global variable) with the maximum value between its current value and the currentPathSum
.
Return Value:
Return the sum of the current node's value and the larger of its left or right subtree sums. This represents the maximum path sum that can be extended to its parent node.
O(n): Each node is visited once.
O(h): Where h
is the height of the tree (due to recursion stack).
How would you modify this solution to track the path that produces the maximum sum?
Can this solution be converted into an iterative approach using a stack?
You can find the full solution here