Python Binary Trees


Binary Tree is a tree data structure where each node has at most two children:

  • A left child

  • A right child

Binary trees are widely used in searching, sorting, and hierarchical data representation.


🔹 Binary Tree Node in Python

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

🔹 Creating a Binary Tree

root = Node(10)
root.left = Node(5)
root.right = Node(15)

✅ Tree structure:

      10
     /  \
    5    15

🔹 Traversing a Binary Tree

🔸 Inorder Traversal (Left → Root → Right)
def inorder(node):
    if node:
        inorder(node.left)
        print(node.data, end=' ')
        inorder(node.right)

inorder(root)  # Output: 5 10 15

🔸 Preorder Traversal (Root → Left → Right)
def preorder(node):
    if node:
        print(node.data, end=' ')
        preorder(node.left)
        preorder(node.right)

🔸 Postorder Traversal (Left → Right → Root)
def postorder(node):
    if node:
        postorder(node.left)
        postorder(node.right)
        print(node.data, end=' ')

🔸 Level Order Traversal (Breadth-First)
from collections import deque

def level_order(root):
    if root is None:
        return
    queue = deque([root])
    while queue:
        current = queue.popleft()
        print(current.data, end=' ')
        if current.left:
            queue.append(current.left)
        if current.right:
            queue.append(current.right)

🔹 Inserting a New Node

def insert(root, value):
    if root is None:
        return Node(value)
    if value < root.data:
        root.left = insert(root.left, value)
    else:
        root.right = insert(root.right, value)
    return root

🔹 Binary Tree Use Cases

  • Expression trees

  • Parsing syntax trees

  • Binary search trees (BST)

  • File directory structures

  • Game trees (AI)


Practice Questions

Q1. Write a Python program to create a binary tree manually by defining node class and linking nodes.

Q2. Write a Python program to perform Inorder traversal on the binary tree and print the result.

Q3. Write a Python program to define and use Preorder and Postorder traversal functions.

Q4. Write a Python program to count all nodes present in the binary tree.

Q5. Write a Python program to insert a node into the correct position in a Binary Search Tree.

Q6. Write a Python program to check if the binary tree is empty.

Q7. Write a Python program to find the maximum value present in the binary tree.

Q8. Write a Python program to print all leaf nodes in the binary tree.

Q9. Write a Python program to use level-order traversal (BFS) to print the tree from top to bottom.

Q10. Write a Python program to build a binary tree from a list of numbers (in level order).


Go Back Top