Skip to main content

Maximum Sum BST in Binary Tree

Problem

Given a binary tree root, 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.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
public:
int ans = 0;
bool f(TreeNode *root, int &minv, int &maxv, int &s) {
if (root == NULL) return true;

int lmin = minv, lmax = maxv, lsum = 0;
bool l = f(root->left, lmin, lmax, lsum);

int rmin = minv, rmax = maxv, rsum = 0;
bool r = f(root->right, rmin, rmax, rsum);

if (l == false || r == false || root->val <= lmax || root->val >= rmin)
return false;

s += lsum + rsum + root->val;
ans = max(ans, s);

minv = min(lmin, root->val);
maxv = max(rmax, root->val);
return true;
}

int maxSumBST(TreeNode *root) {
int s = 0;
int lm = INT_MAX, rm = INT_MIN;
f(root, lm, rm, s);
return ans;
}
};