Start learning free

LESSON 478 OF 667 · BINARY TREES

Maximum Sum BST in Binary Tree: C++ Solution and Time Complexity Analysis

Practice O(n2) Read the full explanation

You get the root of a binary tree. Return the largest sum of values in a subtree that is a binary search tree (BST).

A subtree is a node together with everything below it. It is a BST when this holds at each of its nodes:

  • every value in the node's left subtree is smaller than the node's value,
  • every value in its right subtree is larger.

An empty tree also counts as a BST, with a sum of 0. So the answer is never below 0.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as NULL.

 

Example 1:

6 9 3 4 11 2 1 5

Input: root = [6,9,3,4,11,NULL,2,1,5]
Output: 30
Explanation: The blue subtree starts at 9.
It is a BST: 1 < 4 < 5 < 9 < 11.
Its sum is 9 + 4 + 11 + 1 + 5 = 30.
The whole tree is not a BST: 9 is left of 6 but larger.
The subtree from 3 down is not a BST: 2 is right of 3 but smaller.

Example 2:

-5 -8 4 -9 7

Input: root = [-5,-8,4,-9,7]
Output: 7
Explanation: The subtree from -8 down is a BST, but its sum is -10.
The whole tree is not a BST: 7 is left of -5 but larger.
The best BST is the single blue node 7.

Example 3:

Input: root = [-3,-6,-1]
Output: 0
Explanation: The whole tree is a BST, but every value is negative.
So any BST with nodes in it has a sum below 0.
The empty tree, with sum 0, is the best.

 

Constraints:

  • 1 to 25,000 nodes.
  • Each value is from -10,000 to 10,000.
  • The tree can be up to 10,000 levels deep.
STEP 1 OF 21
    Ctrl + Enter to check

    C++ · BINARY TREES

    Max Sum Bst in C++, explained

    Understanding the Problem

    The core challenge of this problem is to identify the largest sum of keys in any subtree that is a valid Binary Search Tree (BST). A BST is defined by the properties that all nodes in the left subtree are less than the root, and all nodes in the right subtree are greater than the root. Both subtrees must also be BSTs.

    This problem is significant in various applications such as database indexing, where BST properties are used to maintain sorted data for efficient retrieval.

    Potential pitfalls include incorrectly identifying BSTs or not considering all possible subtrees.

    Approach

    To solve this problem, we can use a recursive approach to traverse the tree and check for BST properties. A naive solution would involve checking every possible subtree, which is inefficient. Instead, we can use a post-order traversal to gather information about each subtree and determine if it forms a BST.

    We will use a helper function that returns multiple values: whether the subtree is a BST, the sum of the subtree, the minimum value in the subtree, and the maximum value in the subtree. This information allows us to efficiently determine if a larger subtree is a BST and calculate its sum.

    Algorithm

    The algorithm involves a post-order traversal of the tree. For each node, we recursively check its left and right subtrees. We then use the information from these subtrees to determine if the current subtree is a BST and calculate its sum if it is.

    Here is a step-by-step breakdown:

    1. Define a helper function that returns a tuple containing whether the subtree is a BST, the sum of the subtree, the minimum value in the subtree, and the maximum value in the subtree.
    2. For each node, recursively call the helper function on its left and right children.
    3. Check if the current node forms a BST with its left and right subtrees using the information returned by the helper function.
    4. If it forms a BST, calculate the sum of the current subtree and update the maximum sum if this sum is greater.
    5. Return the appropriate values to the parent call.

    Code Implementation

    #include <iostream>
    #include <tuple>
    #include <algorithm>
    #include <climits>
    
    using namespace std;
    
    // Definition for a binary tree node.
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode() : val(0), left(nullptr), right(nullptr) {}
        TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
        TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    };
    
    class Solution {
    public:
        int maxSumBST(TreeNode* root) {
            int maxSum = 0;
            postOrderTraversal(root, maxSum);
            return maxSum;
        }
    
    private:
        // Helper function to perform post-order traversal and check BST properties
        tuple postOrderTraversal(TreeNode* node, int& maxSum) {
            if (!node) {
                return {true, 0, INT_MAX, INT_MIN}; // Base case: empty subtree
            }
    
            auto [leftIsBST, leftSum, leftMin, leftMax] = postOrderTraversal(node->left, maxSum);
            auto [rightIsBST, rightSum, rightMin, rightMax] = postOrderTraversal(node->right, maxSum);
    
            if (leftIsBST && rightIsBST && node->val > leftMax && node->val < rightMin) {
                int currentSum = node->val + leftSum + rightSum;
                maxSum = max(maxSum, currentSum);
                int currentMin = min(node->val, leftMin);
                int currentMax = max(node->val, rightMax);
                return {true, currentSum, currentMin, currentMax};
            } else {
                return {false, 0, 0, 0}; // Not a BST
            }
        }
    };
    
    int main() {
        // Example usage:
        TreeNode* root = new TreeNode(1);
        root->left = new TreeNode(4);
        root->right = new TreeNode(3);
        root->left->left = new TreeNode(2);
        root->left->right = new TreeNode(4);
        root->right->left = new TreeNode(2);
        root->right->right = new TreeNode(5);
        root->right->right->left = new TreeNode(4);
        root->right->right->right = new TreeNode(6);
    
        Solution sol;
        cout << "Maximum Sum BST: " << sol.maxSumBST(root) << endl;
    
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the number of nodes in the tree. This is because we visit each node exactly once during the post-order traversal.

    The space complexity is O(h), where h is the height of the tree. This is due to the recursive call stack, which can go as deep as the height of the tree.

    Edge Cases

    Potential edge cases include:

    • Empty tree: The function should return 0.
    • All negative values: The function should return 0 if no positive sum BST exists.
    • Single node tree: The function should return the value of the single node if it is positive.

    These cases are handled by the base case in the helper function and the conditions checking for BST properties.

    Testing

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

    • Simple trees with a few nodes.
    • Trees with all negative values.
    • Large trees with mixed values.
    • Edge cases such as empty trees and single node trees.

    Using a testing framework like Google Test can help automate and manage these test cases effectively.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller subproblems.
    • Use recursive approaches for tree problems, as they naturally fit the structure of trees.
    • Think about the properties of the data structure (e.g., BST properties) and how they can be used to simplify the problem.
    • Practice similar problems to build intuition and improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to solve the problem of finding the maximum sum BST in a binary tree using a recursive approach. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving problem-solving skills and preparing for technical interviews.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free