Problem Description
Given a binary tree, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). 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.
Key Insights
- Use a post-order traversal to gather information (validity, sum, min, and max) for each subtree.
- For each node, determine if its subtree is a BST by comparing node values against the maximum of the left subtree and the minimum of the right subtree.
- Maintain a global variable to track the highest BST sum encountered during traversal.
- Return an empty BST (sum = 0) if all valid BSTs result in a negative sum.
Space and Time Complexity
Time Complexity: O(n), as each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack.
Solution
We perform a post-order traversal of the tree. For each node, we recursively inspect its left and right subtrees. Each recursive call returns a tuple (or equivalent structure) containing:
- A boolean indicating whether the subtree is a BST.
- The sum of all node values in the subtree.
- The minimum value in the subtree.
- The maximum value in the subtree.
A node's subtree is a BST if:
- Both left and right subtrees are BSTs.
- The node's value is greater than the maximum value in the left subtree.
- The node's value is less than the minimum value in the right subtree.
If valid, update the global maximum sum with the current BST subtree sum. Otherwise, mark the subtree as invalid. This approach leverages recursion and dynamic programming principles to efficiently evaluate each subtree.