Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogleFacebook

Convert BST to Greater Tree

Choose your preparation mode3 modes available
Steps
setup

Initialize variables

Initialize the accumulated sum to 0, create an empty stack, and set the current node to the root (node with value 4).

💡 Setting up these variables is essential to start the iterative reverse inorder traversal and keep track of the sum of visited nodes.
Line:acc_sum = 0 stack = [] node = root
💡 The algorithm will use the stack to simulate recursion and acc_sum to accumulate node values.
📊
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 fillAnswer 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.