问题描述
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
输出: 42
解题思路
拿到本题,首先确定一个“轴点”,假设我们以根节点(root)为轴点,那么接下来在左右子树中分别寻找“从根节点(root->left,root-<right)到叶子节点的最大路径和”记为left、right,那么以root为轴点的最大路径和为root->val+left+right。
因此我们只需要以二叉树中的各个节点做“轴点”,找出最大路径即可。
ac代码
/**
* 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; //存储以每个节点为root的最大路径
int maxPathSum(TreeNode* root) {
if(root==NULL)
return 0;
maxPath=INT_MIN;
int rootMax=helper(root); //这个值只在递归中有用
return maxPath;
}
int helper(TreeNode* root){
//返回以每个节点为起点向下的最大路径和
if(root==NULL)
return 0;
int left,right;
left=max(0,helper(root->left));
right=max(0,helper(root->right));
if(left+right+root->val>maxPath){
maxPath=left+right+root->val;
}
return max(left,right)+root->val;
}
};