Binary Tree Maximum Path Sum --- LeetCode
来源:互联网 发布:第十四届网络夏令营 编辑:程序博客网 时间:2024/05/22 00:27
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
.
解题思路: 题目要求:找出一棵二叉树上的一条路径,该路径上的节点值和为最大,输出这个最大值。
解题思路:遍历二叉树,从下到上递归计算每个节点的最大值:
max{节点值,节点值+左子树,节点值+右子树,节点值+左右子树}
记录最大值maxValue, 同时将以该节点为头结点的路径最大值返回,递归计算上一层节点:
max{节点值,节点值+左子树,节点值+右子树}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int maxValue=0;
public int maxSum(TreeNode node){
if(node==null){
return 0;
}
int value=node.val;
int leftSum=0;
int rightSum=0;
if(node.left!=null){
leftSum=maxSum(node.left);
if(leftSum>0){
value+=leftSum;
}
}
if(node.right!=null){
rightSum=maxSum(node.right);
if(rightSum>0){
value+=rightSum;
}
}
if(value>maxValue){
maxValue=value;
}
return Math.max(node.val, Math.max(node.val+leftSum, node.val+rightSum));
}
public int maxPathSum(TreeNode root) {
if(root==null){
return 0;
}
maxValue=root.val;
maxSum(root);
return maxValue;
}
}
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- Mysql 服务丢失后,手动添加服务 及启动服务!
- Codeigniter的一些优秀实践
- 【QT】固定窗口大小
- Android 相册图片 添加应用到分享列表
- 超低功耗 无线测温模块 无线测温系统, 待机数年无需更换电池
- Binary Tree Maximum Path Sum --- LeetCode
- 限制只能输入整数、小数的输入框
- 04-性能测试过程
- Android中获取应用程序(包)的信息-----PackageManager的使用(一)
- 键盘退出方式 键盘遮挡
- lua table中可以有函数
- android 耳机按钮监听
- 获取屏幕和布局的高宽度
- [JS]jQuery中attr和prop方法的区别