Binary Tree Maximum Path Sum
2015-07-31 22:22
218 查看
原题:Binary Tree Maximum Path Sum
来自leetcode:https://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,
Return
解:
/**
* 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 getMax(TreeNode * root, int &ans){
if(root==NULL)
return 0;
//需要跟0比较,保证左链大于等于0
int left_chain=max(0, getMax(root->left, ans));
int right_chain=max(0, getMax(root->right, ans));
//需要跟0比较,且前面保证了left_chain以及right_chain大于等于0
ans=max(0, left_chain+root->val+right_chain);
//仍然要返回以当前根节点的左右子链和的最大值,因为root不一定是根节点,只有真正的根节点才可以返回
return max(left_chain+root->val, right_chain+root->val);
}
int maxPathSum(TreeNode* root) {
if(root==NULL)
return 0;
int ans=(-1<<31);
getMax(root, ans);
return ans;
}
};
来自leetcode:https://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 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 getMax(TreeNode * root, int &ans){
if(root==NULL)
return 0;
//需要跟0比较,保证左链大于等于0
int left_chain=max(0, getMax(root->left, ans));
int right_chain=max(0, getMax(root->right, ans));
//需要跟0比较,且前面保证了left_chain以及right_chain大于等于0
ans=max(0, left_chain+root->val+right_chain);
//仍然要返回以当前根节点的左右子链和的最大值,因为root不一定是根节点,只有真正的根节点才可以返回
return max(left_chain+root->val, right_chain+root->val);
}
int maxPathSum(TreeNode* root) {
if(root==NULL)
return 0;
int ans=(-1<<31);
getMax(root, ans);
return ans;
}
};
相关文章推荐
- Android之使用Http协议实现文件上传功能
- 菜鸟说给菜鸟听之Beginning Linux Programming——Chapter1(1)
- sqlserver FOR XML PATH 语句的应用
- set_include_path在win和linux下的区别
- 浅析Cookie中的Path与domain
- cookie中的path与domain属性详解
- PHP include_path设置技巧分享
- NodeJS学习笔记之(Url,QueryString,Path)模块
- 浅析JAVA_HOME,CLASSPATH和PATH的作用
- Python中os.path用法分析
- nginx中path模式配置示例
- JAVA环境变量详解
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Canvas、Path 和 Paint 实例 (游戏开发必备)
- 自动生成AWR HTML报告
- 修改Tomcat的默认访问目录
- Android画图Path的使用_1