124. Binary Tree Maximum Path Sum

Given a 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 containat least one nodeand does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return6.

Analysis:

postorder traversal.

  1. calculate left path sum, right path sum (one way path)
  2. see which one is bigger, root.val OR root.val + left OR root.val + right (the bigger one is the return value for this level)
  3. update maxSum with comparison to result from 2
  4. update maxSum with comparison to root.val + left + right
  5. return maxSum when done;

Complexity:

Time: O(N)

Space: O(logn)

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int maxSum = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if(root == null){
            return 0;
        }
        pathSum(root);
        return maxSum;
    }

    private int pathSum(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftPath = pathSum(root.left);
        int rightPath = pathSum(root.right);
        int greaterSum = Math.max(leftPath, rightPath);
        greaterSum = Math.max(root.val, greaterSum + root.val);
        maxSum = Math.max(maxSum, greaterSum);
        maxSum = Math.max(maxSum, root.val + leftPath + rightPath);
        return greaterSum;
    }
}

results matching ""

    No results matching ""