124. Binary Tree Maximum Path Sum
124. Binary Tree Maximum Path Sum
problem description
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:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
algorithm thought
还是典型的树问题,使用递归解决。
这里题目有点描述不清楚,这里只有根节点可以连接两个子树,也就是加上子树上计算的结果。但是如果是中间节点,那就只能连接一个子树,选择左子树或者右子树。这里当然是选择最大的一个子树。
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res;
int maxtosum(TreeNode* root){
if(root==NULL)
return 0;
int l=maxtosum(root->left);
int r=maxtosum(root->right);
if(l<0) l=0;
if(r<0) r=0;
if(root->val+l+r>res) res=root->val+l+r;
return root->val+=max(l,r);
}
int maxPathSum(TreeNode* root) {
res=INT_MIN;
maxtosum(root);
return res;
}
};
algorithm analysis
对所有的节点遍历一遍得出结果,时间复杂度O(n)
Last updated