题目描述:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
题目思路:
Given the below binary tree:
1
/ \
2 3
return 6
.
这题因为path可以起始/终止于任何一个node,似乎不太好下手。但是可以发现,无论怎样,path都会经过某些node。那如果对于某一node,它的左子树(包含左节点)出一条path(这条path必须不能同时包含左子树的左右子树),右子树(包含右节点)出一条path,那么max可能是左path,或者右path,或者只是这个node本身,或者是左path+node+右path。
Mycode(AC = 51ms):
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
// write your code here
if (root == NULL) {
return 0;
}
int max_sum = INT_MIN;
maxPathSum(root, max_sum);
return max_sum;
}
int maxPathSum(TreeNode *root, int& max_sum) {
if (!root->left && !root->right) {
max_sum = max(max_sum, root->val);
return root->val;
}
int left = INT_MIN, right = INT_MIN, result = INT_MIN;
// get the max path from left subtree (include left node)
if (root->left) {
left = maxPathSum(root->left, max_sum);
result = max(root->val, root->val + left);
}
// get the max path from right subtree (include right node)
if (root->right) {
right = maxPathSum(root->right, max_sum);
result = max(result, max(root->val, root->val + right));
}
if (left != INT_MIN && right != INT_MIN) {
max_sum = max(left + right + root->val, max(max_sum, result));
}
else {
max_sum = max(max_sum, result);
}
return result;
}
};