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
分析
题目的意思是:
给出一个二叉树,找出节点和最大的路径。
- 这虽然是一个二叉树遍历的过程,但是结点的值可能为负数,这样我们在计算最大路径值的时候,要注意把求和为负值的分支舍去,保留返回为正值的分支。
- 递归的代码写得非常的简洁漂亮,这种编程模式在刷题的时候经常看见,最好记住。
C++实现
/**
* 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 {
int sum=INT_MIN;
public:
int maxPathSum(TreeNode* root) {
preorder(root);
return sum;
}
int preorder(TreeNode* root){
if(!root){
return 0;
}
int left=max(0,preorder(root->left));
int right=max(0,preorder(root->right));
sum=max(sum,root->val+left+right);
return max(left,right)+root->val;
}
};
Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorder(self, root):
if not root:
return 0
left_gain = max(self.postorder(root.left),0)
right_gain = max(self.postorder(root.right),0)
self.res = max(self.res, left_gain+right_gain+root.val)
return max(left_gain,right_gain)+root.val
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.res = float('-inf')
self.postorder(root)
return self.res