地址:https://leetcode.com/problems/binary-tree-maximum-path-sum/
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
给定二叉树,求最大路径总和。
可以考虑递归。在每个结点处,分别获得左子树和右子树的最大路径和,加上当前的val,得到当前结点的最大路径和。遍历所有结点,找到最大的即可。由于结点可能出现负值,因此每次要和0比较。代码如下:
/**
* 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 maxPath;
int helper(TreeNode* root){
if(!root) return 0;
int left=max(helper(root->left),0);
int right=max(helper(root->right),0);
maxPath=max((left+right+root->val),maxPath);
return max(left,right)+root->val;
}
int maxPathSum(TreeNode* root) {
maxPath=INT_MIN;
helper(root);
return maxPath;
}
};