Given a 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.
For example:
Given the below binary tree,
1
/ \
2 3
class Solution {
public:
int maxPathSum(TreeNode* root) {
if(!root) return 0;
int m=-2147483648;
maxPath(root,m);
return m;
}
int maxPath(TreeNode* root,int &m){//这里的m要是引用
if(!root) return 0;
int a=maxPath (root->left,m);
int b=maxPath(root->right,m);
if(a<0) a=0;
if(b<0) b=0;
if(a+b+root->val>m) m=a+b+root->val;
return root->val+max(a,b);
}
};
给定一棵二叉树,找出其最大路径和。路径可以始于任意节点,但必须沿着父节点与子节点的连接,并至少包含一个节点,不一定要经过根节点。例如,给定的二叉树中存在这样的最大路径:1 -> 2 -> 3,其路径和为6。
345

被折叠的 条评论
为什么被折叠?



