🔹 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:
50 → 30 → 70 → 20 → 40 → 60 → 80
🔧 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:
50
/ \
30 70
/ \ / \
20 40 60 80
🧠 Python Code:
class Node:
def __init__(self, key):
self.left = self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
# Insert nodes
root = Node(50)
for key in [30, 70, 20, 40, 60, 80]:
insert(root, key)
✅ Tip:
Always start from the root, compare, and go left/right until an empty spot is found.
No comments:
Post a Comment