Tensorum
LeetCode 1373 · Tree

Maximum Sum BST in Binary Tree

LeetCode 1373 · Hard · solution, intuition & step-by-step walkthrough

Post-order returning (sum, min, max) or 'not a BST'.

HardDynamic ProgrammingTreeDepth-First SearchBinary Search TreeBinary Tree
168 msruntime · beats 5%
74.7 MBmemory · beats 100%
1approach
13accepted runs · last 30 Jun 2024

This is how I solved Maximum Sum BST in Binary Tree (LeetCode 1373), a hard problem from the Tree pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Post-order: each subtree reports whether it's a BST, along with its sum, minimum and maximum. A node forms a BST if both children do and the left max < node < right min; then its sum is a candidate. Any invalid child makes every ancestor invalid too.

Approach

  1. 1

    None → empty (valid, no bounds).

  2. 2

    If either child is invalid, return invalid.

  3. 3

    Check left.max < val < right.min.

  4. 4

    Valid → sum, update the best, return new bounds.

How I solved it

Post-order BST infoPythonO(n) time · O(h) space
class Solution:
    def maxSumBST(self, root):
        self.mx = 0

        def dfs(root):
            if root is None:
                return None
            ldata = dfs(root.left)
            rdata = dfs(root.right)
            if ldata is False or rdata is False:
                return False
            isBST = (ldata["max"] < root.val if ldata else True) and (rdata["min"] > root.val if rdata else True)
            if isBST:
                total = (ldata["sum"] if ldata else 0) + (rdata["sum"] if rdata else 0) + root.val
                self.mx = max(total, self.mx)
                return {"sum": total, "min": ldata["min"] if ldata else root.val, "max": rdata["max"] if rdata else root.val}
            return False
        dfs(root)
        return self.mx
Loading the step-through…

Maximum Sum BST in Binary Tree — FAQ

What is the intuition behind Maximum Sum BST in Binary Tree?

Post-order: each subtree reports whether it's a BST, along with its sum, minimum and maximum. A node forms a BST if both children do and the left max < node < right min; then its sum is a candidate. Any invalid child makes every ancestor invalid too.

How do you solve Maximum Sum BST in Binary Tree (LeetCode 1373)?

1. None → empty (valid, no bounds). 2. If either child is invalid, return invalid. 3. Check left.max < val < right.min. 4. Valid → sum, update the best, return new bounds.

What is the time and space complexity of Maximum Sum BST in Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: Post-order BST info.)

What are common mistakes in Maximum Sum BST in Binary Tree?

The best sum starts at 0 — an all-negative tree returns 0 (empty BST).