leetcode-124:Binary Tree Maximum Path Sum(Java)
来源:互联网 发布:php模板引擎与java 编辑:程序博客网 时间:2024/05/28 16:30
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,
解法:动态规划,对每一个节点,以该节点为根节点的最大值设为value,其左子树的路径最大值为lmax,右子树的路径最大值为rmax,(!!! 注意:这里的lmax和rmax指的是从左/右子节点出发的某一条单向路径,例如对于节点4,lmax=2+3 rmax=6+7+8,而并不是lmax=1+2+3 rmax=5+6+7+8)那么有:
value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ;
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.math.*;public class Solution { int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(root == null) return 0; getMaxSumWithCurNode(root); return maxSum; } int getMaxSumWithCurNode(TreeNode curNode){ int lmax = 0, rmax = 0; int value = curNode.val; // 包含当前节点的最大路径和 if(curNode.left != null){ lmax = getMaxSumWithCurNode(curNode.left); } if(curNode.right != null){ rmax = getMaxSumWithCurNode(curNode.right); } value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ; if(value > maxSum) maxSum = value; // 注意这里的返回值,取左右子树其中一条路径 return curNode.val+Math.max( lmax>0?lmax:0, rmax>0?rmax:0 ); }}
0 0
- [Leetcode] Binary Tree Maximum Path Sum (Java)
- [LeetCode][Java] 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 [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
- 深入理解JavaScript系列(25):设计模式之单例模式
- GCC在C语言中内嵌汇编 asm __volatile__
- 初识Cocos2D-X
- UI入门——简单登陆界面,注册界面及找回密码界面铺设以及切换
- 【c++版数据结构】之双链表的实现(带头结点以及尾节点)
- leetcode-124:Binary Tree Maximum Path Sum(Java)
- 深入理解JavaScript系列(26):设计模式之构造函数模式
- light oj 1317
- ACM大一练习赛-第三场------G - EPR悖论<克鲁斯卡尔算法>
- linux内核转储的设置、调试
- Convert QWERTY to Dvorak ZOJ 3878
- 最长连续三字符子串问题
- cv::imdecode 效率问题
- 深入理解JavaScript系列(27):设计模式之建造者模式