问题描述
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
return 6
解决思路
定义一个全局变量存储最大值的路径。利用递归,每次递归返回对应节点的最大路径值,在递归中需要更新全部最大值路径。值得注意的是,这里存在负数的情况。。。需要判断一下条件,如果左右子树都返回负数,则递归返回的是该节点的值就好。。。- 代码
/**
* 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 m;
int maxPathSum(TreeNode* root) {
if (!root)
return 0;
m = INT_MIN;
int l_len = helper(root->left);
int r_len = helper(root->right);
int count = root->val;
if (l_len > 0)
count += l_len;
if (r_len > 0)
count += r_len;
if (count > m)
m = count;
return m;
}
int helper(TreeNode* root) {
if (!root)
return 0;
if (!root->left && !root->right) {
if (root->val > m)
m = root->val;
return root->val;
}
int l_len = helper(root->left);
int r_len = helper(root->right);
int count = root->val;
if (l_len > 0)
count += l_len;
if (r_len > 0)
count += r_len;
if (count > m)
m = count;
if (max(l_len,r_len) >0)
return max(l_len,r_len)+root->val;
else
return root->val;
}
};