How to implement a binary tree?

Anirban Chatterjee
2 min readMar 27, 2023

--

Implementing a binary tree in Python can be done using classes and objects. Here is an example of a binary tree class:

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

In this example, we define two classes: Node and BinaryTree. Node represents a single node in the binary tree, with three attributes: left, right, and data. The left and right attributes point to the left and right child nodes, respectively, and the data attribute stores the value of the node.

The BinaryTree class represents the entire binary tree and has one attribute: root. The root attribute points to the root node of the tree. We initialize the BinaryTree class by passing in the value of the root node.

To add nodes to the binary tree, we can define a method insert in the BinaryTree class. Here is an example implementation of the insert method:

class BinaryTree:
def __init__(self, data):
self.root = Node(data)

def insert(self, data):
node = Node(data)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
curr_node = queue.pop(0)
if curr_node.left is None:
curr_node.left = node
break
else:
queue.append(curr_node.left)
if curr_node.right is None:
curr_node.right = node
break
else:
queue.append(curr_node.right)

In this implementation, we first create a new Node object with the value of the data we want to insert. We then check if the binary tree is empty. If it is, we set the new node as the root of the tree. If the binary tree is not empty, we perform a breadth-first search to find the first empty spot in the tree and insert the new node there.

Here is an example of how to create a binary tree and add nodes to it:

tree = BinaryTree(1)
tree.insert(2)
tree.insert(3)
tree.insert(4)
tree.insert(5)

This creates a binary tree with the following structure:

    1
/ \
2 3
/ \
4 5

I hope this helps you understand how to implement a binary tree in Python!

--

--