Convert BST to Greater Tree - Problem

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

  • 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 — Basic BST
$ Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
💡 Note: For each node, add sum of all greater values. Node 4 becomes 4+5+6+7+8=30, node 1 becomes 1+2+3+4+5+6+7+8=36, etc.
Example 2 — Smaller BST
$ Input: root = [0,null,1]
Output: [1,null,1]
💡 Note: Node 0 becomes 0+1=1 (sum of greater values), node 1 stays 1 (no greater values exist)
Example 3 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Single node has no greater values, so it remains unchanged

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -104 ≤ Node.val ≤ 104
  • All the values in the tree are unique
  • root is guaranteed to be a valid binary search tree

Visualization

Tap to expand
Convert BST to Greater Tree INPUT BST 4 1 6 0 2 5 7 3 8 root = [4,1,6,0,2,5,7, null,null,null,3,null,null,null,8] Left < Node < Right In-order: 0,1,2,3,4,5,6,7,8 REVERSE IN-ORDER DFS 1 Visit Right Subtree First Process larger values before 2 Maintain Running Sum Track sum of visited nodes 3 Update Current Node node.val += runningSum 4 Visit Left Subtree Process smaller values after Traversal Order (Right-Node-Left): 8 --> 7 --> 6 --> 5 --> 4 --> 3 --> 2 --> 1 --> 0 Sum accumulates: 8,15,21,26,30,33,35,36,36 Example: Node 4 sum before = 26 (from 8+7+6+5) new val = 4 + 26 = 30 sum after = 30 GREATER TREE RESULT 30 36 21 36 35 26 15 33 8 [30,36,21,36,35,26,15, null,null,null,33,null,null,null,8] OK - Converted! Time: O(n) | Space: O(h) Key Insight: Reverse in-order traversal (Right-Node-Left) visits BST nodes in descending order. By maintaining a running sum of all visited nodes, each node automatically gets the sum of all greater values added to it. No extra data structure needed - just a single variable! TutorialsPoint - Convert BST to Greater Tree | Reverse In-Order DFS Approach
Asked in
Amazon 15 Facebook 12 Google 8 Microsoft 6
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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