Leetcode Binary Tree Maximum Path Sum
2014-07-01 21:20
253 查看
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,
Return
对于每个结点,我们需要比较三个值。
左结点为结尾的路径和+当前结点值
右结点为结尾的路径和+当前结点值
当前结点值
取这个三个值作为以当前节点为结尾的最大路径和返回。
同时获取以当前结点为根的子树的最大路径和,其子树最大路径来源于
以当前结点为结尾的最大路径和(也就是上面结点所述的值)
左节点为结尾的路径和+当前结点值+右结点为结尾的路径和
左子树的最大路径和
右子树的最大路径和
取其4个值中得最大值作为子树的最大路径和。
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
- 【leetcode】Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum leetcode java
- leetcode 124 —— Binary Tree Maximum Path Sum
- LeetCode "Binary Tree Maximum Path Sum"
- LeetCode Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum 解题报告
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum 解题报告
- leetcode-124:Binary Tree Maximum Path Sum(Java)
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode124:Binary Tree Maximum Path Sum
- leetcode — binary-tree-maximum-path-sum
- Binary Tree Maximum Path Sum(LeetCode)
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- LeetCode binary-tree-maximum-path-sum