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 Tree INPUT Binary Tree Structure 1 4 3 2 4 2 5 4 6 Valid BST subtree Not valid BST Input Array: [1,4,3,2,4,2,5,null,null,... null,null,null,null,4,6] ALGORITHM STEPS Optimized DFS - Single Pass 1 Post-order DFS Process left, right, then node Returns: (isBST, min, max, sum) 2 BST Validation Check: leftMax < node < rightMin Both children must be BST 3 Calculate Sum If valid BST: sum = left + right + node.val 4 Track Maximum Update global max with current BST sum Max BST Found: 3 2 5 +4, +6 below FINAL RESULT Maximum Sum BST Subtree 3 2 5 4 6 Sum = 3+2+5+4+6 Output: 20 OK - Maximum BST Sum Found in single DFS pass Time: O(n), Space: O(h) Key Insight: Post-order traversal allows bottom-up validation: each node receives BST info from children (min, max, sum, isBST) and can determine if current subtree is BST in O(1) time. Track global maximum sum while traversing. Single pass achieves O(n) time complexity. TutorialsPoint - Maximum Sum BST in Binary Tree | Optimized DFS - Single Pass
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