124. Binary Tree Maximum Path Sum

Link

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Solution

這題有點backTracking的影子。

但是最後結果直接更新再global variable max

主要是要想到一個helper(TreeNode node) function 計算從node出發的最大sum為合。

然後在計算的過程由於知道左子樹跟右子樹的最大sum,可以得知假設max的狀況是經過這個node,

那max = node.val + left + right

    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return max;
    }
    
    //return the maxValue oriented by node, 0 if negative
    int helper(TreeNode node){
        if(node == null) return 0;
        int left = Math.max(helper(node.left), 0);
        int right = Math.max(helper(node.right), 0);
        max = Math.max(max, node.val + left + right); //assume the maxPath pass through node, the sum value would be
        // left side nodes sum + node.val + right side nodes sum
        return node.val + Math.max(left, right);
    }

Last updated

Was this helpful?