Binary Tree Maximum Path Sum 二叉树中任意路径的最大和
2015-10-07 22:08
459 查看
Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//左右递归计算 注意根可以不包括在内 所以实时更新
int maxRes;
int maxPathSum(TreeNode* root) {
maxRes=INT_MIN;
solve(root);
return maxRes;
}
int solve(TreeNode *root){
int ans=INT_MIN;//返回当前的最大值
if(root==NULL){
return ans;
}else if(root->left==NULL){// 只有一个节点
int tmp=solve(root->right);
ans= tmp<0?root->val:(root->val+tmp);//返回当前的最大值
if(ans > maxRes){//更新整个最大值
maxRes = ans;
}
}else if(root->right==NULL){
int tmp=solve(root->left);
ans = tmp<0?root->val:(root->val+tmp);//返回当前的最大值
if(ans > maxRes){//更新整个最大值
maxRes = ans;
}
}else {
int leftMax=solve(root->left);
int rightMax=solve(root->right);
int maxTmp=leftMax<rightMax?rightMax:leftMax;
ans = maxTmp<0?root->val:(maxTmp+root->val);//返回当前的最大值
if(ans > maxRes){//1个节点和根节点,更新整个最大值
maxRes = ans;
}
if((leftMax+rightMax+root->val) > maxRes){//两个节点时,更新整个最大值
maxRes=leftMax+rightMax+root->val;
}
}
return ans;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解