Tree Traversal Techniques
Last Updated :
31 Jul, 2024
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses.
.webp)
Tree Traversal Meaning:
Tree Traversal refers to the process of visiting or accessing each node of the tree exactly once in a certain order. Tree traversal algorithms help us to visit and process all the nodes of the tree. Since tree is not a linear data structure, there are multiple nodes which we can visit after visiting a certain node. There are multiple tree traversal techniques which decide the order in which the nodes of the tree are to be visited.
Tree Traversal Techniques:

A Tree Data Structure can be traversed in following ways:
- Depth First Search or DFS
- Inorder Traversal
- Preorder Traversal
- Postorder Traversal
- Level Order Traversal or Breadth First Search or BFS
Inorder traversal visits the node in the order: Left -> Root -> Right

Algorithm for Inorder Traversal:
Inorder(tree)
- Traverse the left subtree, i.e., call Inorder(left->subtree)
- Visit the root.
- Traverse the right subtree, i.e., call Inorder(right->subtree)
Uses of Inorder Traversal:
- In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order.
- To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used.
- Inorder traversal can be used to evaluate arithmetic expressions stored in expression trees.
Code Snippet for Inorder Traversal:
C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
// Function to perform inorder traversal
void inorderTraversal(Node* root) {
// Empty Tree
if (root == nullptr)
return;
// Recur on the left subtree
inorderTraversal(root->left);
// Visit the current node
cout << root->data << " ";
// Recur on the right subtree
inorderTraversal(root->right);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
inorderTraversal(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to perform inorder traversal
void inorderTraversal(struct Node* root) {
// Empty Tree
if (root == NULL)
return;
// Recur on the left subtree
inorderTraversal(root->left);
// Visit the current node
printf("%d ", root->data);
// Recur on the right subtree
inorderTraversal(root->right);
}
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\n");
return 0;
}
Java
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class GfG {
// Function to perform inorder traversal
static void inorderTraversal(Node node) {
// Base case
if (node == null)
return;
// Recur on the left subtree
inorderTraversal(node.left);
// Visit the current node
System.out.print(node.data + " ");
// Recur on the right subtree
inorderTraversal(node.right);
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
inorderTraversal(root);
}
}
Python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to perform inorder traversal
def inorderTraversal(root):
# Base case: if null
if root is None:
return
# Recur on the left subtree
inorderTraversal(root.left)
# Visit the current node
print(root.data, end=" ")
# Recur on the right subtree
inorderTraversal(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inorderTraversal(root)
C#
using System;
class Node {
public int data;
public Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class GfG {
// Function to perform inorder traversal
static void inorderTraversal(Node node) {
// Base case
if (node == null)
return;
// Recur on the left subtree
inorderTraversal(node.left);
// Visit the current node
Console.Write(node.data + " ");
// Recur on the right subtree
inorderTraversal(node.right);
}
public static void Main(string[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
inorderTraversal(root);
}
}
JavaScript
// Define the structure for the Node
class Node {
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to perform inorder traversal
function inorderTraversal(node)
{
// Base case
if (node == null)
return;
// Recur on the left subtree
inorderTraversal(node.left);
// Visit the current node
console.log(node.data);
// Recur on the right subtree
inorderTraversal(node.right);
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
inorderTraversal(root);
Time Complexity: O(N)
Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.
Preorder traversal visits the node in the order: Root -> Left -> Right

Algorithm for Preorder Traversal:
Preorder(tree)
- Visit the root.
- Traverse the left subtree, i.e., call Preorder(left->subtree)
- Traverse the right subtree, i.e., call Preorder(right->subtree)
Uses of Preorder Traversal:
- Preorder traversal is used to create a copy of the tree.
- Preorder traversal is also used to get prefix expressions on an expression tree.
Code Snippet for Preorder Traversal:
C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to perform preorder traversal
void preorderTraversal(Node* root) {
// Base case
if (root == nullptr)
return;
// Visit the current node
cout << root->data << " ";
// Recur on the left subtree
preorderTraversal(root->left);
// Recur on the right subtree
preorderTraversal(root->right);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
preorderTraversal(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to perform preorder traversal
void preorderTraversal(struct Node* root) {
// Base case
if (root == NULL)
return;
// Visit the current node
printf("%d ", root->data);
// Recur on the left subtree
preorderTraversal(root->left);
// Recur on the right subtree
preorderTraversal(root->right);
}
struct Node* newNode(int data) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
preorderTraversal(root);
return 0;
}
Java
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class GfG {
// Function to perform preorder traversal
static void preorderTraversal(Node node) {
// Base case
if (node == null)
return;
// Visit the current node
System.out.print(node.data + " ");
// Recur on the left subtree
preorderTraversal(node.left);
// Recur on the right subtree
preorderTraversal(node.right);
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
preorderTraversal(root);
}
}
Python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to perform preorder traversal
def preorderTraversal(root):
# Base case
if root is None:
return
# Visit the current node
print(root.data, end=' ')
# Recur on the left subtree
preorderTraversal(root.left)
# Recur on the right subtree
preorderTraversal(root.right)
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
preorderTraversal(root)
C#
using System;
class Node {
public int data;
public Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class GfG {
// Function to perform preorder traversal
static void PreorderTraversal(Node node) {
// Base case
if (node == null)
return;
// Visit the current node
Console.Write(node.data + " ");
// Recur on the left subtree
PreorderTraversal(node.left);
// Recur on the right subtree
PreorderTraversal(node.right);
}
public static void Main(string[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
PreorderTraversal(root);
}
}
JavaScript
class Node {
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to perform preorder traversal
function preorderTraversal(node)
{
// Base case
if (node === null)
return;
// Visit the current node
console.log(node.data + " ");
// Recur on the left subtree
preorderTraversal(node.left);
// Recur on the right subtree
preorderTraversal(node.right);
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
preorderTraversal(root);
Time Complexity: O(N)
Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.
Postorder traversal visits the node in the order: Left -> Right -> Root

Algorithm for Postorder Traversal:
Algorithm Postorder(tree)
- Traverse the left subtree, i.e., call Postorder(left->subtree)
- Traverse the right subtree, i.e., call Postorder(right->subtree)
- Visit the root
Uses of Postorder Traversal:
- Postorder traversal is used to delete the tree. See the question for the deletion of a tree for details.
- Postorder traversal is also useful to get the postfix expression of an expression tree.
- Postorder traversal can help in garbage collection algorithms, particularly in systems where manual memory management is used.
Code Snippet for Postorder Traversal:
C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to perform postorder traversal
void postorderTraversal(Node* node) {
// Base case
if (node == nullptr)
return;
// Recur on the left subtree
postorderTraversal(node->left);
// Recur on the right subtree
postorderTraversal(node->right);
// Visit the current node
cout << node->data << " ";
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
postorderTraversal(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to perform postorder traversal
void postorderTraversal(struct Node* node) {
// Base case
if (node == NULL)
return;
// Recur on the left subtree
postorderTraversal(node->left);
// Recur on the right subtree
postorderTraversal(node->right);
// Visit the current node
printf("%d ", node->data);
}
struct Node* newNode(int data) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
postorderTraversal(root);
return 0;
}
Java
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class GfG {
static void postorderTraversal(Node node) {
// Base case:
if (node == null)
return;
// Recur on the left subtree
postorderTraversal(node.left);
// Recur on the right subtree
postorderTraversal(node.right);
// Visit the current node
System.out.print(node.data + " ");
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
postorderTraversal(root);
}
}
Python
class Node:
# Constructor to create a new node
def __init__(self, data):
# Assign data to this node
self.data = data
# Initialize left and right children as None
self.left = None
self.right = None
# Function to perform postorder traversal
def postorderTraversal(node):
# Base case: if the current node is null, return
if node is None:
return
# Recur on the left subtree
postorderTraversal(node.left)
# Recur on the right subtree
postorderTraversal(node.right)
# Visit the current node
print(node.data, end=' ')
# Main function
def main():
# Creating the tree nodes
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Perform postorder traversal
print("Postorder traversal: ", end='')
postorderTraversal(root)
print()
# Run the main function
if __name__ == "__main__":
main()
C#
using System;
class Node {
public int data;
public Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class TreeTraversal {
// Function to perform postorder traversal
static void PostorderTraversal(Node node) {
// Base case
if (node == null)
return;
// Recur on the left subtree
PostorderTraversal(node.left);
// Recur on the right subtree
PostorderTraversal(node.right);
// Visit the current node
Console.Write(node.data + " ");
}
public static void Main(string[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
PostorderTraversal(root);
}
}
JavaScript
class Node {
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to perform postorder traversal
function postorderTraversal(node)
{
// Base case
if (node === null)
return;
// Recur on the left subtree
postorderTraversal(node.left);
// Recur on the right subtree
postorderTraversal(node.right);
// Visit the current node
console.log(node.data);
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
postorderTraversal(root);
Level Order Traversal visits all nodes present in the same level completely before visiting the next level.

Algorithm for Level Order Traversal:
LevelOrder(tree)
- Create an empty queue Q
- Enqueue the root node of the tree to Q
- Loop while Q is not empty
- Dequeue a node from Q and visit it
- Enqueue the left child of the dequeued node if it exists
- Enqueue the right child of the dequeued node if it exists
Uses of Level Order:
Code Snippet for Level Order Traversal:
C++
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Prints level order traversal
void levelOrderTraversal(Node* root) {
if (!root) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* curr = q.front();
q.pop();
cout << curr->data << " ";
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
}
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->right = new Node(6);
levelOrderTraversal(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Tree Node
struct Node {
int data;
struct Node *left;
struct Node *right;
};
// Queue is implemented using singly
// Linked List
struct QNode {
struct Node *tNode;
struct QNode *next;
};
// Ideally we should not use global variables. We have used here
// to reduce code length. Refer the following link for code
// without globals
// https://ide.geeksforgeeks.org/online-c-compiler/022957c0-7344-4773-b2b9-8c0695418af1
struct QNode *front = NULL;
struct QNode *rear = NULL;
// The following functions are defined later
// in this code
void enqueue(struct Node *tNode);
struct Node *dequeue();
// Function to do level order traversal of given
// Binary Tree using a Queue
void levelOrderTraversal(struct Node* root) {
if (root == NULL) return;
enqueue(root);
while (front != NULL) {
struct Node* curr = dequeue();
printf("%d ", curr->data);
if (curr->left != NULL) enqueue(curr->left);
if (curr->right != NULL) enqueue(curr->right);
}
}
struct Node* newNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->left = node->right = NULL;
return node;
}
struct QNode* newQNode(struct Node* tNode) {
struct QNode* qNode =
(struct QNode*)malloc(sizeof(struct QNode));
qNode->tNode = tNode;
qNode->next = NULL;
return qNode;
}
void enqueue(struct Node *tNode) {
struct QNode* qNode = newQNode(tNode);
if (rear == NULL) {
front = rear = qNode;
} else {
rear->next = qNode;
rear = qNode;
}
}
struct Node* dequeue() {
if (front == NULL) return NULL;
struct Node* tNode = front->tNode;
struct QNode* temp = front;
front = front->next;
if (front == NULL) rear = NULL;
free(temp);
return tNode;
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
levelOrderTraversal(root);
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public class GfG {
static void levelOrderTraversal(Node root) {
if (root == null) return;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node curr = q.poll();
System.out.print(curr.data + " ");
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
levelOrderTraversal(root);
}
}
Python
from collections import deque
# Define a tree node structure
class TreeNode:
def __init__(self, x):
self.value = x
self.left = None
self.right = None
# Function to perform level order traversal
def level_order_traversal(root):
if not root:
return
queue = deque([root])
while queue:
node = queue.popleft()
print(node.value, end=" ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# Example usage
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)
print("Level Order Traversal: ", end="")
level_order_traversal(root)
C#
using System;
using System.Collections.Generic;
// Define a tree node structure
public class TreeNode {
public int Value;
public TreeNode Left;
public TreeNode Right;
public TreeNode(int x) { Value = x; }
}
// Function to perform level order traversal
public class LevelOrderTraversal {
public static void LevelOrder(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
TreeNode node = queue.Dequeue();
Console.Write(node.Value + " ");
if (node.Left != null) queue.Enqueue(node.Left);
if (node.Right != null) queue.Enqueue(node.Right);
}
}
public static void Main() {
// Example usage
TreeNode root = new TreeNode(1);
root.Left = new TreeNode(2);
root.Right = new TreeNode(3);
root.Left.Left = new TreeNode(4);
root.Left.Right = new TreeNode(5);
root.Right.Right = new TreeNode(6);
Console.Write("Level Order Traversal: ");
LevelOrder(root);
}
}
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Function to perform level order traversal
function levelOrderTraversal(root) {
if (!root) return;
let queue = [];
queue.push(root);
while (queue.length > 0) {
let node = queue.shift();
console.log(node.value + " ");
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
// Example usage
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
console.log("Level Order Traversal: ");
levelOrderTraversal(root);
Other Tree Traversals:
- Boundary Traversal
- Diagonal Traversal
Boundary Traversal of a Tree includes:
- left boundary (nodes on left excluding leaf nodes)
- leaves (consist of only the leaf nodes)
- right boundary (nodes on right excluding leaf nodes)
Algorithm for Boundary Traversal:
BoundaryTraversal(tree)
- If root is not null:
- Print root’s data
- PrintLeftBoundary(root->left) // Print the left boundary nodes
- PrintLeafNodes(root->left) // Print the leaf nodes of left subtree
- PrintLeafNodes(root->right) // Print the leaf nodes of right subtree
- PrintRightBoundary(root->right) // Print the right boundary nodes
Uses of Boundary Traversal:
- Boundary traversal helps visualize the outer structure of a binary tree, providing insights into its shape and boundaries.
- Boundary traversal provides a way to access and modify these nodes, enabling operations such as pruning or repositioning of boundary nodes.
In the Diagonal Traversal of a Tree, all the nodes in a single diagonal will be printed one by one.
Algorithm for Diagonal Traversal:
DiagonalTraversal(tree):
- If root is not null:
- Create an empty map
- DiagonalTraversalUtil(root, 0, M) // Call helper function with initial diagonal level 0
- For each key-value pair (diagonalLevel, nodes) in M:
- For each node in nodes:
- Print node’s data
DiagonalTraversalUtil(node, diagonalLevel, M):
- If node is null:
- Return
- If diagonalLevel is not present in M:
- Create a new list in M for diagonalLevel
- Append node’s data to the list at M[diagonalLevel]
- DiagonalTraversalUtil(node->left, diagonalLevel + 1, M) // Traverse left child with increased diagonal level
- DiagonalTraversalUtil(node->right, diagonalLevel, M) // Traverse right child with same diagonal level
Uses of Diagonal Traversal:
- Diagonal traversal helps in visualizing the hierarchical structure of binary trees, particularly in tree-based data structures like binary search trees (BSTs) and heap trees.
- Diagonal traversal can be utilized to calculate path sums along diagonals in a binary tree.
Frequently Asked Questions (FAQs) on Tree Traversal Techniques:
1. What are tree traversal techniques?
Tree traversal techniques are methods used to visit and process all nodes in a tree data structure. They allow you to access each node exactly once in a systematic manner.
2. What are the common types of tree traversal?
The common types of tree traversal are: Inorder traversal, Preorder traversal, Postorder traversal, Level order traversal (Breadth-First Search)
3. What is Inorder traversal?
Inorder traversal is a depth-first traversal method where nodes are visited in the order: left subtree, current node, right subtree.
4. What is preorder traversal?
Preorder traversal is a depth-first traversal method where nodes are visited in the order: current node, left subtree, right subtree.
5. What is postorder traversal?
Postorder traversal is a depth-first traversal method where nodes are visited in the order: left subtree, right subtree, current node.
6. What is level order traversal?
Level order traversal, also known as Breadth-First Search (BFS), visits nodes level by level, starting from the root and moving to the next level before traversing deeper.
7. When should I use each traversal technique?
Inorder traversal is often used for binary search trees to get nodes in sorted order.
Preorder traversal is useful for creating a copy of the tree.
Postorder traversal is commonly used in expression trees to evaluate expressions.
Level order traversal is helpful for finding the shortest path between nodes.
8. How do I implement tree traversal algorithms?
Tree traversal algorithms can be implemented recursively or iteratively, depending on the specific requirements and programming language being used.
9. Can tree traversal algorithms be applied to other tree-like structures?
Yes, tree traversal algorithms can be adapted to traverse other tree-like structures such as binary heaps, n-ary trees, and graphs represented as trees.
10. Are there any performance considerations when choosing a traversal technique?
Performance considerations depend on factors such as the size and shape of the tree, available memory, and specific operations being performed during traversal. In general, the choice of traversal technique may affect the efficiency of certain operations, so it’s important to choose the most suitable method for your specific use case.
Some other important Tutorials: