[Leetcode] Binary tree maximum path sum求二叉树最大路径和

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

Return6.

思路:题目中说明起始节点可以是任意节点,所以,最大的路径和不一样要经过root,可以是左子树中某一条,或者是右子树中某一条,当然也可能是经过树的根节点root的。递归式是应该是这三者中选出最大者。这题是看完yucoding的博客才算可能理解,这里只是用中文讲解该博客中的分析过程。举例子:

[Leetcode] Binary tree maximum path sum求二叉树最大路径和

对树中的任一节点,当有一条路径经过它时(不一定为最大),有两种情况:

1)“顶节点”为当前节点时,如当前节点为2时,路径为6->4->2->5->-3;

2)“顶节点”为当前节点的父节点1,当前节点为2时,路径为-3->5->2->1->-3->6

对某个节点a,最大路径为:

i) max_top(a)为第一种情况下的最大路径和;

ii) max_single(a)为第二种情况下的最大路径和;

则,max_top(a)=Max{max_single(a), max_single(a->left)+max_single(a->right)+a->val, a->val};

max_single(a)=Max{max_single(a->left)+a->val, max_single(a->right)+a->val, a->val};

最每个节点a,res=max(res, max_top(a))。

其实,个人这样理解的,以当前点为“顶结点”,则,需从只有一条子树的和、两条子树加顶点的和、该顶点的值三种中选出最大值作为所求值;若以当前点的父结点为顶结点,说明这条路径必须经过该父结点,所以,求经过当前结点的路径,只能是从叶结点到当前结点(再到父结点),即只有一条而不能是两条之和,若是再求两条之后,则后续就不能通过该父结点了。

 /**
* Definition for binary tree
* 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 = root->val;
maxPathSumDFS(root, res);
return res;
}
int maxPathSumDFS(TreeNode *root, int &res) {
if (!root) return ;
int left = maxPathSumDFS(root->left, res);
int right = maxPathSumDFS(root->right, res);
int top = root->val + (left > ? left : ) + (right > ? right : ); //第一种
res = max(res, top);
return max(left, right) > ? max(left, right) + root->val : root->val; //第二种
}
};

//代码来源Grandyang

上一篇:LeetCode Binary Tree Maximum Path Sum 二叉树最大路径和(DFS)


下一篇:SQL行转列与列转行(转)