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.

Input & Output

Example 1 — Mixed Tree
$ Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
💡 Note: The maximum sum BST is the subtree rooted at node 3: [3,2,5,null,null,4,6] with sum 3+2+5+4+6 = 20
Example 2 — Invalid Root BST
$ Input: root = [4,3,null,1,2]
Output: 2
💡 Note: Root is not a valid BST. The maximum sum BST is the single node with value 2, so sum = 2
Example 3 — Negative Values
$ Input: root = [-4,-2,1,1,3,-2,null,-1,null,null,null,2,5,null,null]
Output: 8
💡 Note: The maximum sum BST is [1,-2,5,2] with sum 1+(-2)+5+2 = 6, but actually the BST [1,null,3] gives sum 4, and BST [5] gives 5, so we need to find the actual maximum

Constraints

  • The number of nodes in the tree is in the range [1, 4 × 104]
  • -4 × 104 ≤ Node.val ≤ 4 × 104

Visualization

Tap to expand
Maximum Sum BST in Binary Tree143242546Invalid BSTValid BST: sum = 20Valid BST Subtrees:[3,2,5,4,6] = 20[2] = 2[4] = 4[6] = 6Maximum = 20Result: 20 (sum of largest valid BST subtree)
Understanding the Visualization
1
Input Tree
Binary tree with mixed valid/invalid BST subtrees
2
Identify BSTs
Find all valid BST subtrees and calculate their sums
3
Maximum Sum
Return the largest sum among all valid BST subtrees
Key Takeaway
🎯 Key Insight: Use single DFS to validate BSTs and track sums simultaneously, avoiding redundant tree traversals
Asked in
Amazon 15 Facebook 12 Google 8
78.2K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen