DSA Series Chapter 18 – INSERTION IN BINARY TREE (LEVEL ORDER, Python Version)

 


DSA Series Chapter 18 – INSERTION IN BINARY TREE (LEVEL ORDER, Python Version)

1. Objective

To implement insertion in a Binary Tree using Level Order Traversal (BFS) in Python, ensuring the tree remains complete after every insertion.


2. Why Level Order Insertion in Binary Tree?

A general Binary Tree:

  • Does not follow ordering rules (unlike BST)

  • Must maintain completeness

  • Inserts nodes left to right, level by level

Therefore, Breadth First Search (BFS) is used.


3. Binary Tree Diagram

Before Inserting 6

            1
          /   \
         2     3
        / \
       4   5

After Inserting 6

            1
          /   \
         2     3
        / \   /
       4   5 6

4. Core Logic (Algorithm)

  1. If tree is empty → new node becomes root

  2. Use a queue

  3. Traverse nodes level by level

  4. Insert at the first available left or right position


5. Node Class Definition

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

Explanation

  • data → value of node

  • left, right → references to child nodes


6. Level Order Insertion Function

from collections import deque

def insert_level_order(root, data):
    new_node = Node(data)

    if root is None:
        return new_node

    q = deque()
    q.append(root)

    while q:
        temp = q.popleft()

        if temp.left is None:
            temp.left = new_node
            return root
        else:
            q.append(temp.left)

        if temp.right is None:
            temp.right = new_node
            return root
        else:
            q.append(temp.right)

7. Inorder Traversal (For Verification)

def inorder(root):
    if root:
        inorder(root.left)
        print(root.data, end=" ")
        inorder(root.right)

8. Complete Python Program

from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert_level_order(root, data):
    new_node = Node(data)

    if root is None:
        return new_node

    q = deque()
    q.append(root)

    while q:
        temp = q.popleft()

        if temp.left is None:
            temp.left = new_node
            return root
        else:
            q.append(temp.left)

        if temp.right is None:
            temp.right = new_node
            return root
        else:
            q.append(temp.right)

def inorder(root):
    if root:
        inorder(root.left)
        print(root.data, end=" ")
        inorder(root.right)

# Driver code
root = None
values = [1, 2, 3, 4, 5, 6]

for val in values:
    root = insert_level_order(root, val)

print("Inorder Traversal:")
inorder(root)

9. Output

Inorder Traversal:
4 2 5 1 6 3

10. Time and Space Complexity

Time Complexity

  • O(n) — worst case traversal to find vacant node

Space Complexity

  • O(n) — queue storage


11. Comparison: C vs Python (Insertion)

AspectCPython
QueueManual arraydeque
MemorymallocAutomatic
Root handlingDouble pointerReturn root
ReadabilityModerateHigh

12. Common Student Mistakes

  • Using recursion for insertion

  • Confusing BT insertion with BST insertion

  • Not returning root when tree is empty

  • Forgetting to import deque


13. Exam-Oriented Key Points

  • Binary Tree insertion uses BFS

  • Queue is mandatory

  • Maintains complete binary tree

  • Time complexity: O(n)


14. Learning Outcome

After this post, students can:

  • Insert nodes correctly in a Binary Tree

  • Implement BFS using queue

  • Translate C logic into Python

  • Verify tree structure using traversal

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)


DSA Series Chapter 2 Arrays  (Python Version)

DSA Series Chapter 3 Strings (C Version)


DSA Series Chapter 3 Strings (Python Version)


DSA Series Chapter 4 Linked Lists (Python Version)


DSA Series Chapter 4 Linked Lists (C Version)


DSA Series Chapter 5 Stacks (Python Version)


DSA Series Chapter 5  Stacks  (C Version)




















DSA Series Chapter 13 - Binary Tree traversal, BFS, DFT/DFS, Preorder Traversal In Binary Tree


DSA Series Chapter 14 - InOrder Traversal (Binary Tree C Version)


DSA Series Chapter 14 - InOrder Traversal (Binary Tree Python Version)

 

DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(Python Version)


DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(Python Version)


DSA Seres Chapter 18 : INSERTION IN BINARY TREE (LEVEL ORDER, C Version)


DSA Seres Chapter 19 : INSERTION IN BINARY TREE (LEVEL ORDER, Python Version)








Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights.



Comments