Bird
Raised Fist0
Interview Prepbinary-search-treeseasyAmazonGoogle

Insert into a BST

Choose your preparation mode3 modes available
Steps
setup

Check if tree is empty

The algorithm checks if the root is None. Since the root exists, it proceeds to initialize pointers.

💡 This step handles the edge case of an empty tree by creating a new root if needed.
Line:if root is None: return TreeNode(val)
💡 We know the tree is non-empty, so insertion will be done by traversing existing nodes.
📊
Insert into a BST - Watch the Algorithm Execute, Step by Step
Watching each pointer move and comparison helps you understand how BST insertion preserves order and structure.
Step 1/10
·Active fillAnswer cell
42713
Current node: 1
42713
Current node: 1
42713
Current node: 3
42713
42713
42713
Current node: 6
427135
427135
Return: 1
427135
Result: [1, 2, 3, 4, 5, 7]
427135
Result: [1, 2, 3, 4, 5, 7]
Return: 1

Key Takeaways

Insertion in BST is done by traversing from root to the correct leaf position based on comparisons.

This traversal logic is hard to visualize from code alone but becomes clear when watching pointer moves.

Parent pointer is essential to attach the new node once the correct null child is found.

Understanding the role of parent helps clarify how the tree structure is modified.

Inorder traversal after insertion confirms the BST property is maintained and the new value is correctly placed.

Seeing the sorted output visually confirms correctness beyond just code inspection.