Python Binary Trees


A binary tree is a tree where each node can have at most two children. These children are usually called the left child and the right child. Binary trees are one of the most important data structures because they build the base for several advanced structures like binary search trees, heaps, AVL trees and expression trees. They help in searching, sorting, evaluating expressions and organizing data in an efficient way. Once you understand binary trees, the rest of the tree-based structures become much easier to learn.

In this chapter, you will learn what binary trees are, how nodes are arranged, different types of binary trees, how to build binary tree nodes in Python and how traversal methods work. You will practice several examples and see how binary trees appear in real systems around you.

What Is a Binary Tree?

A binary tree is a hierarchical structure where each node contains:

  • A value

  • A reference to its left child

  • A reference to its right child

A simple binary tree looks like this:

        A
       / \
      B   C
     / \
    D   E

Each node has up to two children. Some nodes may have one child or none.

Key Terms in a Binary Tree

Root

The first node of the tree.

Left Child

The child on the left side of a node.

Right Child

The child on the right side of a node.

Leaf Node

A node with no children.

Internal Node

A node that has at least one child.

Depth

Distance from the root to a specific node.

Height

Longest path from a node down to a leaf.

These terms help when analyzing or building tree operations.

Why Binary Trees Are Important

Binary trees help with:

  • Searching and sorting

  • Building efficient indexing systems

  • Expression evaluation

  • Decision-making algorithms

  • Memory management

  • Organizing structured data

Because each node has only two children, binary trees make traversal and manipulation predictable and fast.

Types of Binary Trees

Binary trees come in many variations. These are the most common ones:

Full Binary Tree

Every node has either 0 or 2 children.

Complete Binary Tree

Every level is filled except possibly the last level.

Perfect Binary Tree

All internal nodes have 2 children, and all leaf nodes are at the same level.

Balanced Binary Tree

The height difference between left and right subtrees is small.

Degenerate Tree

Each node has only one child, making the tree behave like a linked list.

Understanding these variations helps when you study BSTs and AVL trees later.

Creating a Binary Tree Node in Python

Here’s a simple class for a binary tree node:

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

Creating a small binary tree:

root = Node("A")
root.left = Node("B")
root.right = Node("C")

root.left.left = Node("D")
root.left.right = Node("E")

You now have a working structure you can use for traversing and practicing.

Binary Tree Traversal Methods

Traversal means visiting all nodes in a specific order. Binary trees support four popular traversal methods.

Inorder Traversal (Left → Node → Right)

This is the most common traversal for binary search trees because it prints values in sorted order.

def inorder(node):
    if not node:
        return
    inorder(node.left)
    print(node.value)
    inorder(node.right)

Preorder Traversal (Node → Left → Right)

Useful for copying trees or saving them to a file.

def preorder(node):
    if not node:
        return
    print(node.value)
    preorder(node.left)
    preorder(node.right)

Postorder Traversal (Left → Right → Node)

Used in expression tree evaluation.

def postorder(node):
    if not node:
        return
    postorder(node.left)
    postorder(node.right)
    print(node.value)

Level Order Traversal (Breadth-First)

Visits nodes level by level.

from collections import deque

def level_order(root):
    queue = deque([root])
    while queue:
        node = queue.popleft()
        print(node.value)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

This method is simple and extremely useful in many scenarios.

Real-Life Uses of Binary Trees

Binary trees appear in many parts of software systems:

Expression Evaluation

Compilers use binary trees to evaluate mathematical expressions.

Decision Making

AI decision trees commonly use binary structure for branching choices.

Routing Systems

Binary trees help navigation systems optimize path checking.

Memory Allocation

Operating systems store memory segments using tree structures.

File Systems

Some file systems use balanced tree variations for indexing.

The simple two-child rule makes binary trees flexible and powerful.

Building a Small Family Tree Example

root = Node("Grandparent")
root.left = Node("Parent A")
root.right = Node("Parent B")

root.left.left = Node("Child A1")
root.left.right = Node("Child A2")

root.right.left = Node("Child B1")

You can print this structure using an inorder traversal or level order.

Visualizing a Binary Tree with a Simple Print Function

def print_tree(node, level=0):
    if node:
        print_tree(node.right, level + 1)
        print("   " * level + str(node.value))
        print_tree(node.left, level + 1)

This rotates the tree and displays it sideways, making the structure easy to see.

Call it like this:

print_tree(root)

Practical Examples

Example 1: Create a node

node = Node("X")

Example 2: Add left and right children

node.left = Node("Y")
node.right = Node("Z")

Example 3: Build a simple binary tree

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

Example 4: Inorder traversal

inorder(root)

Example 5: Preorder traversal

preorder(root)

Example 6: Postorder traversal

postorder(root)

Example 7: Level order traversal

level_order(root)

Example 8: Build a complete tree

root.left.left = Node(2)
root.left.right = Node(7)

Example 9: Add another right subtree

root.right.left = Node(12)
root.right.right = Node(20)

Example 10: Visual printing

print_tree(root)

Summary of the Tutorial

A binary tree is a structured way to store data where each node can have up to two children. You learned about root, left child, right child, leaves, depth and different types of binary trees. You also created a binary tree node class in Python and explored traversal methods like inorder, preorder, postorder and level order. Binary trees are used in compilers, search engines, AI systems, memory management and many other technologies. With this foundation, you can now move on to binary search trees, where ordering rules make searching extremely fast.


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