Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Balance a Binary Search Tree
Next article icon

Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Tree

Output: 
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 Tree

Output: 
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

Inorder Traversal:

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__ 

Output
Inorder 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

Preorder Traversal:

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__ 

Output
Preorder 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

Postorder Traversal:

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__ 

Output
PostOrder 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


Next Article
Balance a Binary Search Tree

S

sahilgangurde08
Improve
Article Tags :
  • Binary Search Tree
  • Recursion
  • DSA
  • Tree Traversals
Practice Tags :
  • Binary Search Tree
  • Recursion

Similar Reads

    Binary Search Tree
    A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the node’s value. All nodes in the right subtree of a node contain values s
    4 min read
    Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
    Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
    3 min read
    Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
    Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
    15 min read
    Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
    Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
    10 min read
    Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    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 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
    10 min read
    Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
    10 min read
    Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences