二叉树中的最大路径和
2015-08-01 19:18
405 查看
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
class resulttype{
public:
int singlepath;
int maxpath;
resulttype(int x, int y): singlepath(x), maxpath(y)
{}
};
resulttype helper(TreeNode *x){
if (x == nullptr) {
resulttype *m = new resulttype(0, INT_MIN);
return *m;
}
//divide
resulttype left = helper(x -> left);
resulttype right = helper(x -> right);
int sigleft = max(left.singlepath, right.singlepath) + x -> val;
sigleft = max(sigleft, 0);
int maxpa= max(left.maxpath, right.maxpath);
maxpa = max(maxpa, left.singlepath + right.singlepath + x-> val);
resulttype *max = new resulttype(sigleft, maxpa);
return *max;
}
int maxPathSum(TreeNode *root) {
// write your code here
resulttype result= helper(root);
return result.maxpath;
}
};
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
class resulttype{
public:
int singlepath;
int maxpath;
resulttype(int x, int y): singlepath(x), maxpath(y)
{}
};
resulttype helper(TreeNode *x){
if (x == nullptr) {
resulttype *m = new resulttype(0, INT_MIN);
return *m;
}
//divide
resulttype left = helper(x -> left);
resulttype right = helper(x -> right);
int sigleft = max(left.singlepath, right.singlepath) + x -> val;
sigleft = max(sigleft, 0);
int maxpa= max(left.maxpath, right.maxpath);
maxpa = max(maxpa, left.singlepath + right.singlepath + x-> val);
resulttype *max = new resulttype(sigleft, maxpa);
return *max;
}
int maxPathSum(TreeNode *root) {
// write your code here
resulttype result= helper(root);
return result.maxpath;
}
};
相关文章推荐
- AVL树(模板题)—— POJ 3481 Double Queue
- NPM 镜像设置
- Python 学习之列表和元组
- nyoj 20 吝啬的国度
- jmeter http请求界面解释
- 一、IOS程序执行顺序、APPdelegate代理方法执行顺序、ViewController 生命周期
- 理解多线程管理类 CWorkQueue
- 省市联动JQ封装比较简洁调用的方法
- 选择排序之简单选择排序
- hdu 2546饭卡
- mongodb初识
- 正则表达式
- C#隐私信息(银行账户,身份证号码,名字)中间部分特殊字符替换(*)
- Spring源码学习-3.IoC.资源的加载与注册
- X-code7 beta error: warning: Is a directory
- Argument 'xxx' is not a function, got undefined,初学Angular的第一个坑
- Java同步器框架剖析
- [leetcode 70]Climbing Stairs
- 开发并调试 Mail Add-in
- libgdx常用网站