Leetcode052--二叉樹路徑最大和

一、原題


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.




二、中文



找到二叉樹中任意路徑的的和的最大值



三、舉例



比如上的的二叉樹,其最大值就是123的和也就是6



四、思路



從一個結點開始,分別找到它的兩條子路徑的的最大的和,對每個子結點來說,也是這樣,這就形成的遞歸



五、程序


/**
 * 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;
    }
}


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