一、原題
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
Return6.
二、中文
找到二叉樹中任意路徑的的和的最大值
三、舉例
四、思路
從一個結點開始,分別找到它的兩條子路徑的的最大的和,對每個子結點來說,也是這樣,這就形成的遞歸
五、程序
/**
* 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;
maxPathDown(root);
return max;
}
public int maxPathDown(TreeNode node){
if(node == null){
return 0;
}
//選出左邊和右邊的最大的值,然後進行相加
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
max = Math.max(max, left + right + node.val);
//得到該結點和左邊或者右邊比較大那個的和
return Math.max(left, right) + node.val;
}
}