🔹 Rule:
Insert a new node by comparing it with the current node:
-
If smaller → go to left
-
If larger → go to right
-
Repeat until a null spot is found
📘 Example:
Let's insert the following values in this order:
🔧 Step-by-Step Insertion:
-
Insert 50 → becomes root
-
Insert 30 → 30 < 50 → go left
-
Insert 70 → 70 > 50 → go right
-
Insert 20 → 20 < 50 → left → 20 < 30 → left
-
Insert 40 → 40 < 50 → left → 40 > 30 → right
-
Insert 60 → 60 > 50 → right → 60 < 70 → left
-
Insert 80 → 80 > 50 → right → 80 > 70 → right
🌳 Final BST Diagram:
🧠 Python Code:
✅ Tip:
Always start from the root, compare, and go left/right until an empty spot is found.
No comments:
Post a Comment