124. 二叉樹中的最大路徑和(Java)

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

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

示例 1:

輸入: [1,2,3]

       1
      / \
     2   3

輸出: 6
示例 2:

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

   -10
   / \
  9  20
    /  \
   15   7

輸出: 42

 

思路:

遞歸

爲每個點設置一個最大值,表示已這個結點爲中心,這個點的值加上他的左右子樹最大值是多少

返回的也是這個值

 

每次遞歸返回的值是這個點的值和他的max(左子樹值,右子樹值)

 

代碼:

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

class Solution {

    int max = -2147483647>>1;

    public int maxPathSum(TreeNode root) {

        if(root==null) return 0;

        helper(root);

        return max;

    }

    public int helper(TreeNode root){

        if(root==null){

            return 0;

        }

        int left = Math.max(0,helper(root.left));

        int right = Math.max(0,helper(root.right));

 

        int maxnum = root.val+left+right;

        max = Math.max(max,maxnum);

 

        return root.val+Math.max(left,right);

    } 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章