題目:Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.
Binary Tree Maximum Path Sum – LeetCode
解題思路:
1. 設一個max的全局變量記錄遍歷過程中的最大值
2. 對於任意node,計算出它兩棵子樹中的最長單邊路徑,然後三者相加與max比較
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
getMaxSingleBranch(root);
return max;
}
int max = Integer.MIN_VALUE;
// 根節點root 到葉子節點的最長路徑
public int getMaxSingleBranch(TreeNode root) {
if(root == null) return 0;
// root左孩子最長單支路徑
int left = getMaxSingleBranch(root.left);
//..
int right = getMaxSingleBranch(root.right);
//爲負可直接忽略,加上他們只會更小
left = Math.max(left, 0);
right = Math.max(right , 0);
//確定是否更新max
max = Math.max(max,left + right + root.val );
//返回root單支最大路徑
return root.val + Math.max(left , right);
}
}