Maximum Sum BST in Binary Tree: II - Java Solution and Time Complexity Analysis


Given a binary tree root, the task is to return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

 

Example 1:

Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.

Example 2:

Input: root = [4,3,null,1,2]
Output: 2
Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.

Example 3:

Input: root = [-4,-2,-5]
Output: 0
Explanation: All values are negatives. Return an empty BST.

Example 4:

Input: root = [2,1,3]
Output: 6

Example 5:

Input: root = [5,4,8,3,null,6,3]
Output: 7

 

Constraints:

  • Each tree has at most 40000 nodes..
  • Each node's value is between [-4 * 10^4 , 4 * 10^4].

Understanding the Problem

The core challenge of this problem is to identify the sub-trees within a binary tree that are valid Binary Search Trees (BSTs) and then calculate the sum of their nodes. The goal is to find the maximum sum among all such sub-trees.

This problem is significant in various applications such as database indexing, memory management, and more, where BST properties are leveraged for efficient data retrieval and storage.

Potential pitfalls include incorrectly identifying BSTs or missing edge cases where sub-trees might not be valid BSTs.

Approach

To solve this problem, we need to traverse the tree and check each sub-tree to see if it is a valid BST. A naive approach would involve checking each sub-tree individually, which would be highly inefficient.

Instead, we can use a post-order traversal (left-right-root) to gather information about each sub-tree and determine if it forms a valid BST. This allows us to efficiently calculate the sum of nodes for valid BSTs and keep track of the maximum sum encountered.

Naive Solution

The naive solution involves checking each sub-tree individually to see if it is a valid BST and then calculating the sum of its nodes. This approach is not optimal due to its high time complexity.

Optimized Solution

The optimized solution uses a post-order traversal to gather information about each sub-tree. For each node, we check if its left and right sub-trees are valid BSTs and if the current node maintains the BST property. We also calculate the sum of nodes for valid BSTs and update the maximum sum encountered.

Algorithm

Here is a step-by-step breakdown of the optimized algorithm:

  1. Perform a post-order traversal of the tree.
  2. For each node, gather information about its left and right sub-trees (minimum value, maximum value, sum of nodes, and whether it is a valid BST).
  3. Check if the current node forms a valid BST with its left and right sub-trees.
  4. If it does, calculate the sum of nodes for this BST and update the maximum sum encountered.
  5. Return the maximum sum of all valid BSTs in the tree.

Code Implementation

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    // Class to store information about each subtree
    class SubTreeInfo {
        boolean isBST;
        int sum;
        int min;
        int max;
        
        SubTreeInfo(boolean isBST, int sum, int min, int max) {
            this.isBST = isBST;
            this.sum = sum;
            this.min = min;
            this.max = max;
        }
    }
    
    private int maxSum = 0;
    
    public int maxSumBST(TreeNode root) {
        postOrderTraversal(root);
        return maxSum;
    }
    
    private SubTreeInfo postOrderTraversal(TreeNode node) {
        if (node == null) {
            return new SubTreeInfo(true, 0, Integer.MAX_VALUE, Integer.MIN_VALUE);
        }
        
        SubTreeInfo leftInfo = postOrderTraversal(node.left);
        SubTreeInfo rightInfo = postOrderTraversal(node.right);
        
        if (leftInfo.isBST && rightInfo.isBST && node.val > leftInfo.max && node.val < rightInfo.min) {
            int sum = node.val + leftInfo.sum + rightInfo.sum;
            maxSum = Math.max(maxSum, sum);
            int min = Math.min(node.val, leftInfo.min);
            int max = Math.max(node.val, rightInfo.max);
            return new SubTreeInfo(true, sum, min, max);
        } else {
            return new SubTreeInfo(false, 0, 0, 0);
        }
    }
}

Complexity Analysis

The time complexity of the optimized solution is O(n), where n is the number of nodes in the tree. This is because we perform a single post-order traversal of the tree.

The space complexity is O(h), where h is the height of the tree. This is due to the recursive call stack used during the traversal.

Edge Cases

Potential edge cases include:

These edge cases are handled by the algorithm as it checks for null nodes and correctly identifies valid BSTs.

Testing

To test the solution comprehensively, consider the following test cases:

Use testing frameworks such as JUnit to automate the testing process and ensure the solution works for all edge cases.

Thinking and Problem-Solving Tips

When approaching such problems, consider the following tips:

Conclusion

In this blog post, we discussed the problem of finding the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST) in a given binary tree. We explored a naive solution and an optimized solution using post-order traversal. We also analyzed the time and space complexity of the solution and discussed potential edge cases and testing strategies.

Understanding and solving such problems is crucial for developing efficient algorithms and improving problem-solving skills. We encourage readers to practice and explore further to deepen their understanding.

Additional Resources

For further reading and practice problems related to this topic, consider the following resources: