【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
124. 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
/**
* 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 maxPathSum(TreeNode* root)
{
int res = INT_MIN;
helper(root, res); //用res变量存储结果
return res;
}
int helper(TreeNode* node, int& res)
{
if (!node) //结点为空直接返回0
return 0;
//计算左右子树的最大路径和
int left = max(helper(node->left, res), 0); //如果选0,表示不加该子树(子树和为负数)
int right = max(helper(node->right, res), 0);
//更新全局最大值
res = max(res, left + right + node->val); //该全局最大值作为总结果最后输出(通过递归遍历,可以覆盖到经过node的所有路径,node也在变,故可以得到所有路径)
//返回结果
return max(left, right) + node->val; //递归函数返回值的定义是以当前结点为终点的path之和,所以只能取left和right中较大的那个值,而不是两个都要
}
};