Tree Traversal Techniques in Python
Last Updated :
22 Jan, 2024
A tree is a non-linear data structure or we can say that it is a type of hierarchical structure. It is like an inverted tree where roots are present at the top and leaf or child nodes are present at the bottom of the tree. The root node and its child nodes are connected through the edges like the branches in the tree. In this article, we will learn different ways of traversing a tree in Python.
Prerequisites for Tree Traversal in Python

Different Types of Tree Traversal Techniques
There are three types of tree traversal techniques:
- Inorder Traversal in Tree
- Preorder Traversal in Tree
- Postorder Traversal in Tree
Note: These traversal in trees are types of depth first search.
Overview of Tree Traversal Techniques
In the below image we can see a binary tree and the result of each traversal technique. We will be going to understand each technique in detail.

Inorder Tree Traversal in Python
Inorder tree traversal is basically traversing the left, root, and right node of each sub-tree. We can understand it better by using below algorithm:
- Traverse the left subtree by recursively calling the inorder traversal function.
- Visit the root node (usually an action is performed such as printing the node value).
- Traverse the right subtree by recursively calling the inorder traversal function.
Example
The Node
class represents an individual node of the tree, where each node has a left child, a right child, and a data value. The printInorder
function recursively traverses the tree in an inorder manner: it first traverses the left subtree, then visits the current node to print its data value, and finally traverses the right subtree. In the driver code section (if __name__ == "__main__":
), a sample binary tree with seven nodes is constructed and the printInorder
function is called to display the inorder traversal of the tree. The output would be the values of the nodes in the order they are visited using the inorder traversal method.
Python3
# Python3 code to implement the approach
# Class describing a node of tree
class Node:
def __init__(self, v):
self.left = None
self.right = None
self.data = v
# Inorder Traversal
def printInorder(root):
if root:
# Traverse left subtree
printInorder(root.left)
# Visit node
print(root.data,end=" ")
# Traverse right subtree
printInorder(root.right)
if __name__ == "__main__":
# Build the tree
root = Node(10)
root.left = Node(25)
root.right = Node(30)
root.left.left = Node(20)
root.left.right = Node(35)
root.right.left = Node(15)
root.right.right = Node(45)
# Function call
print("Inorder Traversal:",end=" ")
printInorder(root)
OutputInorder Traversal: 20 25 35 10 15 30 45
Pre-Order Tree Traversal in Python
Pre-order tree traversal is basically traversing the Root, Left, and Right node of each sub-tree. We can understand it better by using below algorithm:
- Visit the root node.
- Traverse the left subtree by recursively calling the preorder traversal function.
- Traverse the right subtree by recursively calling the preorder traversal function.
Example:
The given code defines a binary tree and demonstrates the preorder traversal technique. The `Node` class defines each node of the tree with attributes for its data, left child, and right child. The `printPreOrder` function carries out a recursive preorder traversal, which involves: first visiting and printing the current node's data, then traversing the left subtree, followed by traversing the right subtree. In the driver code, a sample binary tree is constructed with nodes having values ranging from 10 to 300. The function `printPreOrder` is then invoked on the root of this tree, printing the nodes in the order dictated by the preorder traversal.
Python3
class Node:
def __init__(self, v):
self.data = v
self.left = None
self.right = None
# Preorder Traversal
def printPreOrder(node):
if node is None:
return
# Visit Node
print(node.data, end = " ")
# Traverse left subtree
printPreOrder(node.left)
# Traverse right subtree
printPreOrder(node.right)
# Driver code
if __name__ == "__main__":
# Build the tree
root = Node(95)
root.left = Node(15)
root.right = Node(220)
root.left.left = Node(10)
root.left.right = Node(30)
root.right.left = Node(160)
root.right.right = Node(285)
# Function call
print("Preorder Traversal: ", end = "")
printPreOrder(root)
OutputPreorder Traversal: 95 15 10 30 220 160 285
Post-Order Tree Traversal using Python
Post-order tree traversal is basically traversing the Left, Right, and Root node of each sub-tree. We can understand it better by using below algorithm:
- Traverse the left subtree by recursively calling the postorder traversal function.
- Traverse the right subtree by recursively calling the postorder traversal function.
- Visit the root node.
Example:
The provided code showcases the postorder traversal method for a binary tree. The `Node` class represents a node in the tree, characterized by its data, left child, and right child. The `printPostOrder` function conducts a recursive postorder traversal on the tree. In this traversal, the left subtree is traversed first, followed by the right subtree, and then the current node's data is visited and printed. This sequence ensures that a node is processed after both its left and right subtrees have been traversed (hence, "postorder"). The driver code constructs a sample binary tree and subsequently calls the `printPostOrder` function to display the result of the postorder traversal of the tree. The nodes' values will be printed in the sequence dictated by the postorder traversal technique.
Python3
class Node:
def __init__(self, v):
self.data = v
self.left = None
self.right = None
# Preorder Traversal
def printPostOrder(node):
if node is None:
return
# Traverse left subtree
printPostOrder(node.left)
# Traverse right subtree
printPostOrder(node.right)
# Visit Node
print(node.data, end = " ")
# Driver code
if __name__ == "__main__":
# Build the tree
root = Node(10)
root.left = Node(2)
root.right = Node(20)
root.left.left = Node(1)
root.left.right = Node(3)
root.right.left = Node(15)
root.right.right = Node(30)
# Function call
print("Postorder Traversal: ", end = "")
printPostOrder(root)
OutputPostorder Traversal: 1 3 2 15 30 20 10
Similar Reads
Recursion on Trees in Python
In Python, recursion is implemented by defining a function that makes a call to itself within its definition. This process continues until a base case is reached, which is a condition where the function returns a value without making any further recursive calls. Without a base case, the recursion wo
8 min read
Tree Sort in Python
Tree sort is a sorting algorithm that builds a Binary Search Tree (BST) from the elements of the array to be sorted and then performs an in-order traversal of the BST to get the elements in sorted order. In this article, we will learn about the basics of Tree Sort along with its implementation in Py
3 min read
Postorder Traversal of Binary Tree in Python
Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root policy such that for each node:The left subtree is traversed firstThen the right subtree is traversedFinally, the root node of the subtree is traversedConsider the following tree: If we perform a postorder t
3 min read
Looping Techniques in Python
Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects that require a specific technique with loops maintaining the overall structure of code. Â A lot of
6 min read
Directory traversal tools in Python
os.walk() method of the OS module can be used for listing out all the directories. This method basically generates the file names in the directory tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames,
2 min read
Rerooting Techniques in Python
Rerooting techniques are typically used in the context of rooted trees in computational problems, such as dynamic programming on trees, network design, and more. The idea is to compute some values for a tree rooted at one node and then efficiently recompute the values for the tree rooted at other no
4 min read
Preorder Traversal of Binary Tree in Python
Preorder traversal is defined as a type of tree traversal that follows the Root-Left-Right policy where:The root node of the subtree is visited first.Then the left subtree is traversed.At last, the right subtree is traversed.Consider the following tree: If we perform a preorder traversal in this bin
3 min read
Inorder Traversal of Binary Tree in Python
Inorder traversal is defined as a type of tree traversal technique which follows the Left-Root-Right pattern, such that:The left subtree is traversed firstThen the root node for that subtree is traversedFinally, the right subtree is traversedConsider the following tree: If we perform an inorder trav
3 min read
Binary Tree Level Order Traversal in C++
Trees are the type of data structure that stores the data in the form of nodes having a parent or children or both connected through edges. It leads to a hierarchical tree-like structure that can be traversed in multiple ways such as âpreorder, inorder, postorder, and level order. A binary tree is a
8 min read
Inorder Tree Traversal in Binary Tree in C
A binary Tree is a hierarchical data structure in which each node has at most two children and it can referred to as the left child and right child. Due to being a non-linear data structure, different traversal techniques are possible for it. Inorder tree traversal is one of the techniques used to v
3 min read