🌱 Insertion in Binary Search Tree (BST)

Follow Me 

🔹 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:

  1. Insert 50 → becomes root

  2. Insert 30 → 30 < 50 → go left

  3. Insert 70 → 70 > 50 → go right

  4. Insert 20 → 20 < 50 → left → 20 < 30 → left

  5. Insert 40 → 40 < 50 → left → 40 > 30 → right

  6. Insert 60 → 60 > 50 → right → 60 < 70 → left

  7. 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

Recursion in DSA using Python

Follow me If you want to understand with  Graphical Representation   click on it. You can find the explanatory video at the bottom of this p...