LeetCode 124 Binary Tree Maximum Path Sum
来源:互联网 发布:软件界面开发工具 编辑:程序博客网 时间:2024/05/01 22:19
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
.
思路:本人脑子笨,一开始想了好久都木有思路,只有一个笨办法:把所有的叶子i到叶子节点j的路径都遍历一遍。最近写回溯法用递归用的多,我突然想到了递归可以。用一个全局变量max来存储最大值,然后再求最大连续子序列和。假设我们已经知道了某个节点node的左右子树的最大路径和leftmaxsum,rightmaxsum,那么这个节点node的最大路径和为Math.max(node.val,Math.max(node.val+leftmaxsum,node.val+rightmaxsum));这个节点node的最大路径和只是为了给node的父节点准备的,并非给node自己准备的。那么给node准备用啥呢---max, temp=root.val+leftmaxsum+rightmaxsum; max=max>temp?max:temp; 这样max就能返回当前的最大路径和。代码如下:
public class Solution {static int max = Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {max = Integer.MIN_VALUE;PathSum(root);return max;}public int PathSum(TreeNode root) {if(root==null) return 0;int leftmaxsum=0;int rightmaxsum=0;int temp=root.val; if(root.left!=null){ leftmaxsum=Math.max(PathSum(root.left),0); } if(root.right!=null){ rightmaxsum=Math.max(PathSum(root.right),0); } temp=root.val+leftmaxsum+rightmaxsum; max=max>temp?max:temp; return Math.max(root.val,Math.max(root.val+leftmaxsum, root.val+rightmaxsum)); }}
0 0
- LeetCode 124: Binary Tree Maximum Path Sum
- LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode: Binary Tree Maximum Path Sum [124]
- LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- [LeetCode 124]Binary Tree Maximum Path Sum
- leetcode || 124、Binary Tree Maximum Path Sum
- LeetCode #124 Binary Tree Maximum Path Sum
- leetcode 124: Binary Tree Maximum Path Sum
- 124 Binary Tree Maximum Path Sum [Leetcode]
- LeetCode 124: Binary Tree Maximum Path Sum
- LeetCode 124:Binary Tree Maximum Path Sum
- LeetCode 124 Binary Tree Maximum Path Sum
- Leetcode 124 Binary Tree Maximum Path Sum
- Leetcode #124 Binary Tree Maximum Path Sum
- Leetcode-124: Binary Tree Maximum Path Sum
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- 推荐几个偷网站的小工具
- poj 3299
- 15款值得学习的小型开源项目,带你快速步入开源世界
- 九度 题目1026:又一版 A+B java
- new 、 delete 、 malloc 、 free
- LeetCode 124 Binary Tree Maximum Path Sum
- IOS真机调试步骤
- 导入ExtJs校验报错的处理办法
- 算法学习,冒泡排序
- 学习笔记:GLSL Core Tutorial – Vertex Shader(内置变量说明)
- android 动画xml属性总结
- 设计模式六大原则
- gbs使用手册之gbs build
- Redhat6的yum安装与配置【转】