1. 程式人生 > >leetcode 24 二叉樹中的最大路徑和

leetcode 24 二叉樹中的最大路徑和

給定一個非空二叉樹,返回其最大路徑和。

本題中,路徑被定義為一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。

示例 1:

輸入: [1,2,3]

       1
      / \
     2   3

輸出: 6

示例 2:

輸入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

輸出: 42

對於任意一個節點, 如果最大和路徑包含該節點, 那麼只可能是兩種情況:
        1. 其左右子樹中所構成的和路徑值較大的那個加上該節點的值後向父節點回溯構成最大路徑
        2. 左右子樹都在最大路徑中, 加上該節點的值構成了最終的最大路徑

class Solution {
    private int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root){
        getMax(root);
        return res;   
    }
    public int getMax(TreeNode r){
        if(r == null) return 0;
        int left = Math.max(0, getMax(r.left)); // 如果子樹路徑和為負則應當置0表示最大路徑不包含子樹
        int right = Math.max(0. getMax(r.right));
        res = Math.max(res, left + right + r.val); // 判斷在該節點包含左右子樹的路徑和是否大於當前最大路徑和
        return Math.max(left + right) + r.val;
    }
}