LeetCode - Binary Tree Maximum Path Sum

2 minute read

Problem description

description

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:

1
2
3
4
5
6
7
Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

1
2
3
4
5
6
7
8
9
Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Analysis

The general idea is to analysis for each node, there are two possible path. One is with its parent to form a path, another one is don’t with it’s parent. So we can use a max to store those without it’s parent and return the other value to it’s parent so that we can do the recursion.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxPathSum(TreeNode root) {
        int v = dfs(root);
        return Math.max(max, v);
    }
    
    int max = Integer.MIN_VALUE;
    
    public int dfs(TreeNode node){
        if (node == null){
            return 0;
        }
        
        if (node.left == null && node.right == null){
            max = Math.max(node.val, max);
            return node.val;
        }
        else if (node.left == null){
            int right = Math.max(0, dfs(node.right));
            max = Math.max(max, right+node.val);
            return right + node.val;
        }
        else if (node.right == null){
            int left = Math.max(0, dfs(node.left));
            max = Math.max(max, left+node.val);
            return left + node.val;
        }
        else {
            int left = Math.max(0, dfs(node.left));
            int right = Math.max(0, dfs(node.right));

            int valNotEndAtNode = Math.max(left, right) + node.val;
            int valEndAtNode = left + right + node.val;
            max = Math.max(valNotEndAtNode, Math.max(max, valEndAtNode));
            
            return valNotEndAtNode;
        }
    }
}

What to improve

  • Note that there’s a possible path which is it only contains node itself.