地址:http://oj.leetcode.com/problems/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
Return 6
.
感觉这道题想通比较难,有提示就好一点,山重水复与柳暗花明只有一步之隔。
参考代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int ans;
int dfs(TreeNode* root)
{
if(!root)
return 0;
int left = dfs(root->left);
int right = dfs(root->right);
int sum = root->val + max(left, 0) + max(right, 0);
ans = max(ans, sum);
return max(max(left, right), 0) + root->val;
}
public:
int maxPathSum(TreeNode *root) {
ans = INT_MIN;
dfs(root);
return ans;
}
};
//SECOND TRIALclass Solution {private :int ans = INT_MIN ;int find_max ( TreeNode * root ){if ( ! root )return 0 ;int left = find_max ( root -> left );int right = find_max ( root -> right );ans = max ( ans , root -> val + max ( 0 , left ) + max ( 0 , right ));return root -> val + max ( 0 , max ( left , right ));}public :int maxPathSum ( TreeNode * root ) {if ( ! root )return 0 ;find_max ( root );return ans ;}};
python:
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = None
class Solution :def __init__ ( self ):self . ans = - 10000000 # since -sys.maxint could not be used in leetcode ojdef dfs ( self , root ):if not root :return 0lval = self . dfs ( root . left )rval = self . dfs ( root . right )self . ans = max ( self . ans , root . val + max ( 0 , lval ) + max ( 0 , rval ))return root . val + max ( 0 , max ( lval , rval ))# @param root, a tree node# @return an integerdef maxPathSum ( self , root ):if not root :return 0 ;self . dfs ( root )return self . ans