描述
給一棵二叉樹,找出從根節(jié)點出發(fā)的路徑中,和最大的一條
這條路徑可以在任何二叉樹中的節(jié)點結(jié)束,但是必須包含至少一個點(也就是根了)
樣例
給出如下的二叉樹:
1
/ \
2 3
返回4。(最大的路徑為1→3)
代碼
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of binary tree.
* @return an integer
*/
public int maxPathSum2(TreeNode root) {
if (root == null) {
// 不能return 0;因為整棵樹的結(jié)點值可能都為負(fù)
return Integer.MIN_VALUE;
}
int left = maxPathSum2(root.left);
int right = maxPathSum2(root.right);
// Math.max(left, right)必須和0比較
// 因為葉子結(jié)點的左右兒子為空
// Math.max(left,right)必定會返回Integer.MIN_VALUE
// 遇到葉子結(jié)點的左右兒子函數(shù)值應(yīng)該返回0
return root.val + Math.max(0, Math.max(left, right));
}
}