leetcode: Binary Tree Maximum Path Sum
2014-06-19 09:52
357 查看
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
考虑经过根节点和不经过根节点两种情况
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 { public: int maxPathSum(TreeNode *root) { if( root == NULL) return 0; int maxi = INT_MIN; core( root, maxi); return maxi; } int core( TreeNode *root, int &maxi){ if( root == NULL) return 0; int leftsum = core( root->left, maxi); int rightsum = core( root->right, maxi); //经过自己,连通左右子树 int rootsum = root->val; rootsum = leftsum > 0 ? leftsum + rootsum : rootsum;//左子树大于0就加上 rootsum = rightsum > 0 ? rightsum + rootsum : rootsum;//右子树大于0就加上 maxi = rootsum > maxi ? rootsum : maxi; //不连通左右子树 int pathsum = root->val; int subsum = max( leftsum, rightsum); pathsum = subsum > 0 ? pathsum + subsum : pathsum; maxi = pathsum > maxi ? pathsum : maxi; return pathsum; } };
相关文章推荐
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- LeetCode: Binary Tree Maximum Path Sum
- Leetcode-binary-tree-maximum-path-sum
- Binary Tree Maximum Path Sum -- LeetCode
- Binary Tree Maximum Path Sum [leetcode] dp
- LeetCode Week5:Recover Binary Search Tree、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第27题(binary-tree-maximum-path-sum)
- [LeetCode] Binary Tree Maximum Path Sum
- LeetCode力扣之124. Binary Tree Maximum Path Sum
- LeetCode No.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