Binary Tree
Data Structures
Tree Implementation
Programming
Algorithm Design

How to implement a binary tree?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. Binary trees are used in a variety of applications, including sorting and searching algorithms, expression parsers, and more. This article explains how to implement a binary tree step-by-step, utilizing examples and detailed explanations.

Binary Tree Structure

Before diving into the implementation, let's discuss the structure of a binary tree. Each node in a binary tree contains three main components:

  1. Data: This is the value stored in the node.
  2. Left Child: A reference to the left subtree.
  3. Right Child: A reference to the right subtree.

Here's an illustration of a basic node class in Python:

python
1class Node:
2    def __init__(self, data):
3        self.data = data
4        self.left = None
5        self.right = None

Building the Binary Tree

To construct a binary tree, we initiate a root node and then add more nodes based on specific conditions or algorithms. Here's a simple binary tree class:

python
1class BinaryTree:
2    def __init__(self):
3        self.root = None
4
5    def insert(self, data):
6        if self.root is None:
7            self.root = Node(data)
8        else:
9            self._insert(self.root, data)
10
11    def _insert(self, node, data):
12        if data < node.data:
13            if node.left is None:
14                node.left = Node(data)
15            else:
16                self._insert(node.left, data)
17        else:
18            if node.right is None:
19                node.right = Node(data)
20            else:
21                self._insert(node.right, data)

Key Points for Insertion

  • Root Node: If the root is None, then the new node becomes the root.
  • Left Child: If the new data is less than the current node's data, traverse to the left.
  • Right Child: If the new data is greater than or equal to the current node's data, traverse to the right.

Traversing the Binary Tree

Tree traversal algorithms are crucial for accessing and manipulating the data stored in a binary tree. The common methods include:

  • In-order Traversal: Left -> Root -> Right
  • Pre-order Traversal: Root -> Left -> Right
  • Post-order Traversal: Left -> Right -> Root
  • Level-order Traversal: Visit nodes level by level

Here’s how you could implement in-order traversal:

python
1def in_order_traversal(node):
2    if node is not None:
3        in_order_traversal(node.left)
4        print(node.data, end=' ')
5        in_order_traversal(node.right)

Tree Operations

Searching

Searching in a binary tree follows a similar pattern to insertion:

python
1def search(node, key):
2    if node is None or node.data == key:
3        return node
4
5    if key < node.data:
6        return search(node.left, key)
7    
8    return search(node.right, key)

Deletion

Deleting a node from a binary tree is a bit more complex as it requires handling three cases:

  1. Node is a Leaf: Simply remove it.
  2. Node has one Child: Remove the node and replace it with its child.
  3. Node has Two Children: Replace the node with its in-order successor or predecessor, then delete the successor/predecessor.

Here's a basic representation of deleting a node:

python
1def delete_node(root, key):
2    if root is None:
3        return root
4
5    if key < root.data:
6        root.left = delete_node(root.left, key)
7    elif key > root.data:
8        root.right = delete_node(root.right, key)
9    else:
10        if root.left is None:
11            return root.right
12        elif root.right is None:
13            return root.left
14
15        temp = find_min(root.right)
16        root.data = temp.data
17        root.right = delete_node(root.right, temp.data)
18
19    return root
20
21def find_min(node):
22    current = node
23    while current.left is not None:
24        current = current.left
25    return current

Summary Table

Here's a table that summarizes the operations discussed along with their functionalities and implementations:

OperationDescriptionImplementation Approach
InsertAdds data to the treeCompare with current node, recurse left/right
In-order TraversalVisits all nodes in ascending orderRecurse: Left, Root, Right
SearchFinds a node with a specific valueCompare with current node, recurse
DeleteRemoves a node and restructures the tree as neededHandle leaf, single child, and two children cases
Find MinimumFinds the smallest value nodeTraverse left until None

Conclusion

Binary trees are fundamental in computer science for organizing data hierarchically. Implementing a binary tree involves understanding its structure and being able to perform essential operations like insertion, traversal, searching, and deletion. Mastering these operations provides a deep understanding of tree-based algorithms, which are widely used in numerous applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.