LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)
2015-10-28 19:56
337 查看
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,
Return
求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用ret全局变量来维护这个最大值。将总体当作根节点加上左边和右边就可以了,代码如下:
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.
求二叉树的最大路径和,感觉好复杂,但是分析一下,由于中间的点不能重叠,所以说肯定一部分在某个点的左边一个在右边。所以可以遍历左右子树来求最大值,相当于遍历所有的单点以及其左右子树之后,不断的更新最大值,用ret全局变量来维护这个最大值。将总体当作根节点加上左边和右边就可以了,代码如下:
class Solution { public: int maxPathSum(TreeNode *root) { if(!root) return ret; ret = INT_MIN; dfs(root); return ret; } int dfs(TreeNode * node) { if(node == NULL) return 0; int val = node->val; int left = dfs(node->left); int right = dfs(node->right); if(left > 0) val += left; if(right > 0) val += right; if(val > ret) ret = val; return max(node->val, max(node->val + left, node->val + right)); } private: int ret; };
相关文章推荐
- 输出高效的日志信息
- Math对象是个organizational object(集合的对象)
- 中国大学MOOC-陈越、何钦铭-数据结构 排序(希尔排序)
- 网页中图片旋转的几种实现方式
- C#操作剪贴板实现复制粘贴
- 状态压缩 UVALive 6068 The Little Girl who Picks Mushrooms (12长春C)
- 杜绝“野指针”
- 如何添加现有的虚拟机到Parallels Desktop中
- 07-图4 哈利·波特的考试
- oracle 卡住不动
- 易犯错让人混淆的指针与Const
- LeetCode 117: Populating Next Right Pointers in Each Node II
- CSS边框素材
- 求一个数二进制中1的个数
- pythony文件操作编码问题
- c# 5.0——async 和 await
- nginx 负载均衡
- 驱动的模块申明
- oracle 卡住不动
- linux基础5