Inorder traversal Python of a Binary Tree

Inorder traversal using python of a tree is as pretty easy if you know the concepts of dictionaries and classes. In this article, we will talk about the Inorder traversal Python of a Tree. Here we will be talking about binary trees.

Tree and its inorder traversal using python.

Binary tree is the tree where one node can have only two children and cannot have more than two. Traversal means visiting all the nodes of the Binary tree. There are three types of traversal.

Let’s take the below tree for example.

Binary Tree and its traversal using python.

Inorder traversal

In order, traversal means visiting first left, then root and then right. If the tree is a binary search tree this will sort the tree in order.

So the traversal of above tree would be 4 2 5 1 3I

These were the traversal now let’s code it in python

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

def inOrder(root):
   if root:
       inOrder(root.left)
       print (root.data)
       inOrder(root.right

#making the tree 
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print inOrder(root)
#4 2 5 1 3

So this is how you write the binary tree in Python.

Let’s have a look at the script.

We made a class Node which represents the node of the Binary tree. We initialize the node with data and left and right child as None.

When we add a new child we simple use root.left or root.left.left to add a new child.

Now let’s have a look at the traversal functions.

In all these functions we took advantage of recursion and passed the subtrees in the functions again to print in proper order.

In Inorder function,  we first pass the left subtree to Inorder then print the node and then pass the right subtree. Thus made left, root and right.

Here we took a look into how to code binary Tree and its traversal using python.

If you like the articles, You can install our app for quick updates.


Gaurav Yadav

Gaurav is cloud infrastructure engineer and a full stack web developer and blogger. Sportsperson by heart and loves football. Scale is something he loves to work for and always keen to learn new tech. Experienced with CI/CD, distributed cloud infrastructure, build systems and lot of SRE Stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.