Problem
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node’s values in the path.
Given the root
of a binary tree, return the maximum path sum of any non-empty path.
Examples
Example 1:
|
|
|
|
Example 2:
|
|
|
|
Solution
Method 1 - DFS
For each node, there are four possible paths for the maximum path sum:
- Only the node itself
- The maximum path through the left child plus the node
- The maximum path through the right child plus the node
- The maximum path through the left child, the node, and the right child
The key is to track these four paths and select the highest value at the end.
Note
It is important to understand that each subtree’s root must return the maximum path sum that includes at most one child. This is necessary for the call to the parent function. In the code below, this sum is called maxOne
and it is what the recursive function returns.
Why don’t we return the sum of node.val + node.left + node.right
(named currTwo
) in the last line? Including currTwo
in the maxPathSum
would violate the principle that each node can be traversed only once. Since it is impossible to traverse from node->left->right->node’s parent without revisiting the node itself, we cannot include currTwo
in the return value.
Code
|
|
|
|
|
|
|
|
Examples
Example 1
Our goal is to find the maximum path sum. Now consider the following example.
|
|
In this simple case we know that the max sum would be just the root node itself and the answer would be 10. So fo all leaf
nodes the max sum path is the value of the node itself.
Example 2
Now let’s consider the following example.
|
|
Here there are multiple possibilities and we need to take care of the following FOUR PATHS that could be our max.
- The root iself :
20
- The root with the maximum from it’s left subTree : = 10 + 20
|
|
- The root with the maximum from it’s right subTree : = 30 + 20
|
|
- The root with it’s left, right and itself = 60
|
|
In case you are wondering why we did not choose the root.left (10) or root.right(30) alone in the calculation ( like I wondered ), that’s because we would have already computed the result of it as a node in our recursion separately.