Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Last Updated :
23 Jul, 2025
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.
Input:
A Binary Search TreeOutput:
Inorder Traversal: 10 20 30 100 150 200 300
Preorder Traversal: 100 20 10 30 200 150 300
Postorder Traversal: 10 30 20 150 300 200 100
Input:
Binary Search TreeOutput:
Inorder Traversal: 8 12 20 22 25 30 40
Preorder Traversal: 22 12 8 20 30 25 40
Postorder Traversal: 8 20 12 25 40 30 22
Below is the idea to solve the problem:
At first traverse left subtree then visit the root and then traverse the right subtree.
Follow the below steps to implement the idea:
- Traverse left subtree
- Visit the root and print the data.
- Traverse the right subtree
The inorder traversal of the BST gives the values of the nodes in sorted order. To get the decreasing order visit the right, root, and left subtree.
Below is the implementation of the inorder traversal.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Class describing a node of tree
class Node {
public:
int data;
Node* left;
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
// Inorder Traversal
void printInorder(Node* node)
{
if (node == NULL)
return;
// Traverse left subtree
printInorder(node->left);
// Visit node
cout << node->data << " ";
// Traverse right subtree
printInorder(node->right);
}
// Driver code
int main()
{
// Build the tree
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
// Function call
cout << "Inorder Traversal: ";
printInorder(root);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
// Class describing a node of tree
class Node {
int data;
Node left;
Node right;
Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
class GFG {
// Inorder Traversal
public static void printInorder(Node node)
{
if (node == null)
return;
// Traverse left subtree
printInorder(node.left);
// Visit node
System.out.print(node.data + " ");
// Traverse right subtree
printInorder(node.right);
}
// Driver Code
public static void main(String[] args)
{
// Build the tree
Node root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
System.out.print("Inorder Traversal: ");
printInorder(root);
}
}
// This code is contributed by Rohit Pradhan
Python
# 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)
# Driver code
if __name__ == "__main__":
# Build the tree
root = Node(100)
root.left = Node(20)
root.right = Node(200)
root.left.left = Node(10)
root.left.right = Node(30)
root.right.left = Node(150)
root.right.right = Node(300)
# Function call
print("Inorder Traversal:",end=" ")
printInorder(root)
# This code is contributed by ajaymakvana.
C#
// Include namespace system
using System;
// Class describing a node of tree
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
public class GFG
{
// Inorder Traversal
public static void printInorder(Node node)
{
if (node == null)
{
return;
}
// Traverse left subtree
GFG.printInorder(node.left);
// Visit node
Console.Write(node.data.ToString() + " ");
// Traverse right subtree
GFG.printInorder(node.right);
}
// Driver Code
public static void Main(String[] args)
{
// Build the tree
var root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
Console.Write("Inorder Traversal: ");
GFG.printInorder(root);
}
}
JavaScript
// JavaScript code to implement the approach
class Node {
constructor(v) {
this.left = null;
this.right = null;
this.data = v;
}
}
// Inorder Traversal
function printInorder(root)
{
if (root)
{
// Traverse left subtree
printInorder(root.left);
// Visit node
console.log(root.data);
// Traverse right subtree
printInorder(root.right);
}
}
// Driver code
if (true)
{
// Build the tree
let root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
console.log("Inorder Traversal:");
printInorder(root);
}
// This code is contributed by akashish__
OutputInorder Traversal: 10 20 30 100 150 200 300
Time complexity: O(N), Where N is the number of nodes.
Auxiliary Space: O(h), Where h is the height of tree
Below is the idea to solve the problem:
At first visit the root then traverse left subtree and then traverse the right subtree.
Follow the below steps to implement the idea:
- Visit the root and print the data.
- Traverse left subtree
- Traverse the right subtree
Below is the implementation of the preorder traversal.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Class describing a node of tree
class Node {
public:
int data;
Node* left;
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
// Preorder Traversal
void printPreOrder(Node* node)
{
if (node == NULL)
return;
// Visit Node
cout << node->data << " ";
// Traverse left subtree
printPreOrder(node->left);
// Traverse right subtree
printPreOrder(node->right);
}
// Driver code
int main()
{
// Build the tree
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
// Function call
cout << "Preorder Traversal: ";
printPreOrder(root);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
// Class describing a node of tree
class Node {
int data;
Node left;
Node right;
Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
class GFG {
// Preorder Traversal
public static void printPreorder(Node node)
{
if (node == null)
return;
// Visit node
System.out.print(node.data + " ");
// Traverse left subtree
printPreorder(node.left);
// Traverse right subtree
printPreorder(node.right);
}
public static void main(String[] args)
{
// Build the tree
Node root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
System.out.print("Preorder Traversal: ");
printPreorder(root);
}
}
// This code is contributed by lokeshmvs21.
Python
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(100)
root.left = Node(20)
root.right = Node(200)
root.left.left = Node(10)
root.left.right = Node(30)
root.right.left = Node(150)
root.right.right = Node(300)
# Function call
print("Preorder Traversal: ", end = "")
printPreOrder(root)
C#
// Include namespace system
using System;
// Class describing a node of tree
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
public class GFG
{
// Preorder Traversal
public static void printPreorder(Node node)
{
if (node == null)
{
return;
}
// Visit node
Console.Write(node.data.ToString() + " ");
// Traverse left subtree
GFG.printPreorder(node.left);
// Traverse right subtree
GFG.printPreorder(node.right);
}
public static void Main(String[] args)
{
// Build the tree
var root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
Console.Write("Preorder Traversal: ");
GFG.printPreorder(root);
}
}
JavaScript
class Node {
constructor(v) {
this.data = v;
this.left = this.right = null;
}
}
function printPreOrder(node) {
if (node == null) return;
console.log(node.data + " ");
printPreOrder(node.left);
printPreOrder(node.right);
}
// Build the tree
let root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
console.log("Preorder Traversal: ");
printPreOrder(root);
// This code is contributed by akashish__
OutputPreorder Traversal: 100 20 10 30 200 150 300
Time complexity: O(N), Where N is the number of nodes.
Auxiliary Space: O(H), Where H is the height of the tree
Below is the idea to solve the problem:
At first traverse left subtree then traverse the right subtree and then visit the root.
Follow the below steps to implement the idea:
- Traverse left subtree
- Traverse the right subtree
- Visit the root and print the data.
Below is the implementation of the postorder traversal:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Class to define structure of a node
class Node {
public:
int data;
Node* left;
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
// PostOrder Traversal
void printPostOrder(Node* node)
{
if (node == NULL)
return;
// Traverse left subtree
printPostOrder(node->left);
// Traverse right subtree
printPostOrder(node->right);
// Visit node
cout << node->data << " ";
}
// Driver code
int main()
{
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
// Function call
cout << "PostOrder Traversal: ";
printPostOrder(root);
cout << "\n";
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
// Class describing a node of tree
class GFG {
static class Node {
int data;
Node left;
Node right;
Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
// Preorder Traversal
public static void printPostOrder(Node node)
{
if (node == null)
return;
// Traverse left subtree
printPostOrder(node.left);
// Traverse right subtree
printPostOrder(node.right);
// Visit node
System.out.print(node.data + " ");
}
public static void main(String[] args)
{
// Build the tree
Node root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
System.out.print("PostOrder Traversal: ");
printPostOrder(root);
}
}
Python
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(100)
root.left = Node(20)
root.right = Node(200)
root.left.left = Node(10)
root.left.right = Node(30)
root.right.left = Node(150)
root.right.right = Node(300)
# Function call
print("Postorder Traversal: ", end = "")
printPostOrder(root)
C#
// Include namespace system
using System;
// Class describing a node of tree
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}
public class GFG
{
// Preorder Traversal
public static void printPostOrder(Node node)
{
if (node == null)
{
return;
}
// Traverse left subtree
GFG.printPostOrder(node.left);
// Traverse right subtree
GFG.printPostOrder(node.right);
// Visit node
Console.Write(node.data.ToString() + " ");
}
public static void Main(String[] args)
{
// Build the tree
var root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
Console.Write("PostOrder Traversal: ");
GFG.printPostOrder(root);
}
}
JavaScript
class Node {
constructor(v) {
this.data = v;
this.left = null;
this.right = null;
}
}
// Preorder Traversal
function printPostOrder(node) {
if (node === null) {
return;
}
// Traverse left subtree
printPostOrder(node.left);
// Traverse right subtree
printPostOrder(node.right);
// Visit Node
console.log(node.data, end = " ");
}
// Driver code
// Build the tree
let root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);
// Function call
console.log("Postorder Traversal: ", end = "");
printPostOrder(root);
// This code is contributed by akashish__
OutputPostOrder Traversal: 10 30 20 150 300 200 100
Time complexity: O(N), Where N is the number of nodes.
Auxiliary Space: O(H), Where H is the height of the tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem