标签:style blog color art for io
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
.
对于每个结点,我们需要比较三个值。
取这个三个值作为以当前节点为结尾的最大路径和返回。
同时获取以当前结点为根的子树的最大路径和,其子树最大路径来源于
取其4个值中得最大值作为子树的最大路径和。
class Solution { public: int maxSum = INT_MIN; int getMaxSum(TreeNode* root){ if(root == NULL) return 0; int leftSum = getMaxSum(root->left), rightSum = getMaxSum(root->right); int curSum = max(root->val, max(root->val+leftSum, root->val+rightSum)); maxSum = max(maxSum,max(curSum,root->val+leftSum+rightSum)); return curSum; } int maxPathSum(TreeNode *root){ getMaxSum(root); return maxSum; } };
Leetcode Binary Tree Maximum Path Sum,布布扣,bubuko.com
Leetcode Binary Tree Maximum Path Sum
标签:style blog color art for io
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3819070.html