Problem
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
This problem is different from the general path sum problem, in this problem, path sum can starts in non-root, and it can also end in non-leaf.
-
This kind of path can be concluded in two types:
root->leaf
path, in example1’s 1->2 or 1->3.- Two nodes are connected by their lowest common ancestor (LCA) node, in example1’s 2->1->3.
-
Apprently, top-down’s recursion method doesn’t work because in type2’s path, its path sum is depends on LCA’s left and right sub path’s maximum, and this type of path sum cannot be obtained from top-down recursion method.
-
Therefore, we can use bottom-up’s recursion method. Let say node x,
- Define
PS1(x)
is from node x to leaf’s first type’s path sum. - Define
PS2(x)
is node x as LCA’s second type path’s path sum. - So, if we find all node x’s
PS1
andPS2
, then we can find the max path sum.
- Define
-
How to find
PS1(x)
andPS2(x)
?PS1(x)
andPS2(x)
are not less thanx-val
becausex
itself can be a single node path.PS1(x)
andPS2(x)
can be found inPS1(x-left)
andPS1(x-right)
:PS1(x) = max [ max(PS1(x->left), 0), max(PS1(x->right), 0) ] + x->val
PS2(x) = max(PS1(x->left), 0) + max(PS1(x->right), 0) + x->val
-
We need to return
PS1(x)
for its upper layer’s node to calculatePS1
andPS2
. -
For leaf node,
PS1(x) = PS2(x) = x->val
.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24class Solution { public: int maxPathSum(TreeNode *root) { int maxSum = INT_MIN; int ps1_root = findMaxPathSum(root, maxSum); return maxSum; } int findMaxPathSum(TreeNode *root, int &maxSum) { if(!root) return 0; int ps1_left = 0, ps1_right = 0; if(root->left) ps1_left = max(findMaxPathSum(root->left,maxSum),0); if(root->right) ps1_right = max(findMaxPathSum(root->right,maxSum),0); int ps1_root = max(ps1_left, ps1_right) + root->val; int ps2_root = ps1_left + ps1_right + root->val; maxSum = max(maxSum,max(ps1_root, ps2_root)); return ps1_root; } };
Solution
1 |
|