Binary Tree Maximum Path Sum

題目: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);

    }
}
發佈了121 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章