124. Binary Tree Maximum Path Sum
题目内容
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.
题目分析
代码
class Solution {
int max_sum;
public:
int maxPathSum(TreeNode* root) {
max_sum = INT_MIN;
traverse(root);
return max_sum;
}
int traverse(TreeNode *node) {
if (node == NULL) return 0;
int left = std::max(0, traverse(node->left));
int right = std::max(0, traverse(node->right));
int sum = node->val + left + right;
max_sum = std::max(sum, max_sum);
return std::max(left + node->val, right + node->val);
}
};