[LeetCode] 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 contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
       1
      / \
     2   3
Return 6.

Thought process:
A path in a tree goes up 0 or more nodes from the start node, and goes 0 or more nodes from the highest node. The idea is to use a recursive method to calculate a node's maximum downward path sum, i.e. when it's the highest node in the path, and use an instance variable to keep track of the max path sum.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * 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) {
        maxPathDown(root);
        
        return maxSum;
    }
    
    private int maxPathDown(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftSum = Math.max(0, maxPathDown(root.left));
        int rightSum = Math.max(0, maxPathDown(root.right));
        
        maxSum = Math.max(maxSum, leftSum + root.val + rightSum);
        
        return Math.max(leftSum, rightSum) + root.val;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula