题目
分析
和上一篇LeetCode算法题很像。使用递归来解。注意只有一个节点时且节点为负数,不能直接返回0
Time Complexity:O(n)
Space ComplexityO(h)
流程
定义一个子函数分别处理子树返回子树的sum,记录最大和。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
int ans = INT_MIN;
maxPathFun(root, ans);
return ans;
}
int maxPathFun(TreeNode* root, int& ans){
if(!root)
return 0;
int l = max(0, maxPathFun(root->left, ans));
int r = max(0, maxPathFun(root->right, ans));
int sum = root->val + l + r;
ans = max(ans, sum);
return root->val + max(l, r);
}
};
python版
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.ans = float('-inf')
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def sum(root):
if root is None:
return 0
l = max(0, sum(root.left))
r = max(0, sum(root.right))
s = l + r + root.val
self.ans = max(self.ans, s)
return max(l, r) + root.val
sum(root)
return self.ans