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
Understanding the Visualization
1
Original BST
Input BST with values [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
2
Calculate Sums
For each node, find sum of all nodes with greater values
3
Updated BST
Each node = original value + sum of greater values
Key Takeaway
🎯 Key Insight: Use reverse in-order traversal to process nodes from largest to smallest, maintaining a running sum for optimal O(n) performance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code