leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
2017-04-10 16:57
453 查看
124. Binary Tree Maximum Path Sum
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 must contain
at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
计算二叉树中的路径之和最大值,起止节点为任意(此题和求二叉树的直径差不多,参考)
543. Diameter of Binary Tree Java版 (二叉树的最大直径)
private int maxVal = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null)
return 0;
maxCore(root);
return maxVal;
}
// 该函数返回是左右的最大路径和,而非左+右+root的最大值
// 使用curValue,来标记左+右+root
private int maxCore(TreeNode root) {
if (root == null)
return 0;
// 求以root为根的当前子树的最大路径和
// 如果左右子树都是负数,
// 那么就最大路径就是当前结点值(无论正负)
int curValue = root.val;
int lmax = maxCore(root.left);
int rmax = maxCore(root.right);
if (lmax > 0)
curValue += lmax;
if (rmax > 0)
curValue += rmax;
maxVal = Math.max(curValue, maxVal);
// 返回以当前root为根的子树的最大路径和
// 左右有可能都为负数,所以需要参与比较大小
int thisMax = Math.max(root.val,
Math.max(lmax + root.val,
rmax + root.val));
return thisMax;
}
相关文章推荐
- Leetcode 124. 二叉树中的最大路径和
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)
- [LeetCode 124] - 二叉树最大路径和(Binary Tree Maximum Path Sum)
- LeetCode(124) Binary Tree Maximum Path Sum 二叉树的最大路径和 (如何递归?)
- 剑指offer解题报告(Java版)——二叉树中和为某一值的路径 25
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- leetcode解题之62&63. Unique Paths ||64. Minimum Path Sum java版(路径(最短)可达)
- Leetcode 654. Maximum Binary Tree 最大二叉树 解题报告
- leetCode 104.Maximum Depth of Binary Tree(二叉树最大深度) 解题思路和方法
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- leetcode解题之 11. Container With Most Water Java版(最大盛水容积)
- 124 Binary Tree Maximum Path Sum 求二叉树的最大路径和
- LeetCode之求二叉树最大路径和
- leetcode解题之329. Longest Increasing Path in a Matrix Java版 (最长上升路径)
- 【leetcode Java】二叉树的递归遍历以及最大深度的求解(Java)
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- Leetcode 104. Maximum Depth of Binary Tree 二叉树的最大高度 解题报告
- Leetcode 124. Binary Tree Maximum Path Sum 最大路径和 解题报告
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径