Convert BST to Greater Tree - Watch the Algorithm Execute, Step by Step
Watching this step-by-step traversal and update process reveals how the algorithm transforms the BST into a Greater Tree by leveraging the BST property and reverse inorder traversal.
Step 1/15
·Active fill★Answer cell
Current node: 1
416025738
Current node: 7
416025738
Current node: 9
416025738
416025788
4160251588
Current node: 6
41210251588
Current node: 5
41210251588
412102651588
Current node: 2
3012102651588
Current node: 8
3012102651588
3012102651588
Current node: 4
30352102651588
Current node: 4
30352102651588
30362136352615338
30362136352615338
Return: 1
Key Takeaways
✓ Reverse inorder traversal (right-root-left) is key to accumulating sums from largest to smallest node values.
This traversal order ensures each node's new value includes all greater values, which is hard to see from code alone.
✓ Using a stack simulates recursion and preserves traversal state explicitly.
Watching the stack grow and shrink clarifies how the algorithm backtracks and processes nodes in correct order.
✓ Node values update immediately upon visiting, reflecting the running sum.
Seeing values change step-by-step helps understand how the accumulated sum affects each node.
Practice
(1/5)
1. You are given a binary search tree and a target integer k. You need to determine if there exist two distinct nodes in the BST whose values sum up to k. Which of the following approaches guarantees an optimal solution in terms of time and space complexity?
easy
A. Perform an inorder traversal to get a sorted array, then use two pointers to find if a pair sums to k.
B. Use dynamic programming to store sums of all subtree pairs and check for k.
C. Perform a brute force nested traversal of all node pairs directly on the BST without extra storage.
D. Use a greedy approach by always choosing the smallest and largest node values and adjusting pointers.
Solution
Step 1: Understand BST property and inorder traversal
Inorder traversal of a BST produces a sorted array of node values.
Step 2: Apply two-pointer technique on sorted array
Using two pointers at start and end, we can efficiently find if two values sum to k in O(n) time and O(n) space.
Final Answer:
Option A -> Option A
Quick Check:
Inorder + two pointers is optimal and uses BST ordering [OK]
Hint: Inorder traversal yields sorted array for two-pointer sum [OK]
Common Mistakes:
Trying nested loops directly on BST nodes without flattening
Assuming greedy approach works without sorting
Using DP which is unnecessary here
2. Consider the following buggy code for inserting a value into a BST. Which line contains the subtle bug that causes the insertion to fail silently in some cases?
def insertIntoBST(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
insertIntoBST(root.left, val)
else:
insertIntoBST(root.right, val)
return root
medium
A. Line 2: if root is None
B. Line 4: if val < root.val
C. Line 7: insertIntoBST(root.right, val)
D. Line 5: insertIntoBST(root.left, val)
Solution
Step 1: Analyze recursive calls
Recursive calls to insertIntoBST on root.left or root.right do not update the parent's child pointer.
Step 2: Identify missing assignment
Lines 5 and 7 call insertIntoBST but do not assign the returned subtree back to root.left or root.right, so insertion is lost.
Hint: Recursive insert must assign returned subtree to parent's child [OK]
Common Mistakes:
Not updating parent's child pointer
Confusing base case with recursive step
Incorrect comparison operator
3. Suppose you want to extend the BST Iterator to support repeated calls to next() that return the same element multiple times (i.e., allow reuse of elements). Which modification to the Morris traversal based iterator is correct?
hard
A. Remove thread restoration to keep the tree threaded and allow repeated visits to the same node.
B. Store all elements in a list during initialization to allow repeated next() calls without traversal.
C. Modify _advance() to not move current pointer after returning next_val, so next() returns same value again.
D. Use a stack-based iterator and push nodes multiple times to simulate repeated next() calls.
Solution
Step 1: Understand reuse requirement
Allowing repeated next() calls to return the same element requires storing elements since Morris traversal advances and loses previous state.
Step 2: Evaluate modifications
Removing thread restoration (A) corrupts tree, modifying _advance() to not move current (C) breaks traversal logic, and pushing nodes multiple times on stack (B) is inefficient and incorrect. Storing all elements upfront (D) enables repeated next() calls reliably.
Final Answer:
Option B -> Option B
Quick Check:
Pre-storing elements supports repeated next() calls without traversal [OK]
Hint: Reuse requires storing elements, not traversal tricks [OK]
Common Mistakes:
Assuming traversal can be paused and repeated
Ignoring tree corruption from missing restoration
Trying to simulate reuse with threads
4. Suppose the BST can contain duplicate values, and you want to find all nodes with a given value. Which modification to the optimal iterative search algorithm correctly finds all such nodes?
hard
A. Stop at the first found node and return it, since duplicates are not allowed in BSTs.
B. Modify the search to continue searching both left and right subtrees even after finding a matching node.
C. Traverse the entire tree recursively to collect all nodes with the target value, ignoring BST property.
D. Use a queue to perform BFS and collect all nodes with the target value efficiently.
Solution
Step 1: Understand duplicates in BST
Duplicates can appear on either left or right subtree depending on BST definition.
Step 2: Modify search to find all matches
After finding a node with val, continue searching both subtrees to find all duplicates.
Step 3: Avoid full traversal
Using BST property to prune search still possible by checking subtrees where duplicates may exist.
Final Answer:
Option B -> Option B
Quick Check:
Continuing search after first match finds all duplicates [OK]
Hint: Duplicates require searching both subtrees after match [OK]
Common Mistakes:
Stopping at first match or ignoring BST property completely
5. Suppose the BST can contain duplicate values and the range is inclusive [low, high]. How should the trimming algorithm be modified to correctly handle duplicates without breaking BST properties?
hard
A. Change all comparisons to strict inequalities (e.g., < low to <= low) to exclude duplicates outside range.
B. Rebuild the BST from scratch after filtering duplicates to ensure correct ordering.
C. Adjust pruning conditions to include nodes equal to low or high by using <= and >= comparisons appropriately.
D. Ignore duplicates during pruning since BST properties guarantee uniqueness.
Solution
Step 1: Understand duplicates in BST
Duplicates can be on left or right subtree depending on implementation; inclusive range means nodes equal to low or high must be kept.
Step 2: Modify pruning conditions
Use <= and >= in comparisons to keep nodes equal to boundaries, ensuring duplicates within range remain.
Step 3: Avoid rebuilding
Rebuilding wastes time and space; pruning with adjusted conditions preserves BST and duplicates correctly.
Final Answer:
Option C -> Option C
Quick Check:
Inclusive pruning keeps duplicates at boundaries [OK]
Hint: Use inclusive comparisons to keep duplicates within range [OK]
Common Mistakes:
Using strict inequalities excludes boundary duplicates
Rebuilding unnecessarily wastes resources
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.