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.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
sum(root);
return max;
}
/**
* sum 方法的两个功能
* 1 计算出以node为根节点能找到的最大值,如果比max大,则max = curValue
* 2 同时要考虑如果该node作为最后结果(path)的一部分,则要找出 以node 为root 的这棵子树中的最大值,
* 即 sum 的返回值
*/
private int sum(TreeNode node) {
if (node == null) {
return 0;
}
int l = sum(node.left);
int r = sum(node.right);
int curValue = node.val;
if (l > 0) {
curValue += l;
}
if (r > 0) {
curValue += r;
}
if (curValue > max) {
max = curValue;
}
//如果左右都为负数,则直接从node 往上找
return Math.max(Math.max(l,r) + node.val, node.val);
}
}
本文介绍了一种算法,用于在给定的二叉树中找到具有最大路径和的路径。路径可以从树的任意节点开始并结束于任意节点。
547

被折叠的 条评论
为什么被折叠?



