124. 二叉树中的最大路径和
题目描述
Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
思路
树的遍历算法会遍历每一个节点,所以,在遍历的过程中以遇到的每一个节点为中心,计算以这个节点为起点的单侧路径的最大值,这相当于枚举了树中每一个节点的情况,顺便更新了最大值,总之是这个函数干了两件事情,函数的返回值是这个函数的功能部分,在函数的调用过程中更新update maxSum是额外间接干的事情。
代码实现
class Solution {
public:
int maxPathSum(TreeNode *root) {
int maxSum = INT_MIN;//初始值
maxPathSumCore(root, maxSum);
return maxSum;
}
int maxPathSumCore(TreeNode*root,int & maxSum)
{
if(root==nullptr)
return 0;
int left = maxPathSumCore(root->left,maxSum);
int right = maxPathSumCore(root->right,maxSum);
int curSum = root->val;
if(left > 0)
curSum+=left;
if(right > 0)
curSum+=right;
if(curSum > maxSum)
maxSum = curSum;
return max(max(left+root->val,right+root->val),root->val);
}
};