Open In App

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

Last Updated : 02 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
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


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)
 
# 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.


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(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 printPreorder(Node node)
  {
    if (node == null)
      return;
 
    // Traverse left subtree
    printPreorder(node.left);
 
    // Traverse right subtree
    printPreorder(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("Preorder Traversal: ");
    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;
        }
        // Traverse left subtree
        GFG.printPreorder(node.left);
        // Traverse right subtree
        GFG.printPreorder(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("Preorder Traversal: ");
        GFG.printPreorder(root);
    }
}


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(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)


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



Previous Article
Next Article

Similar Reads

Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
16 min read
Construct Tree from given Inorder and Preorder traversals
Let us consider the below traversals: Inorder sequence: D B E A F C Preorder sequence: A B D E C FRecommended PracticeConstruct Tree from Inorder &amp; PreorderTry It! In a Preorder sequence, the leftmost element is the root of the tree. So we know 'A' is the root for given sequences. By searching ‘A’ in the Inorder sequence, we can find out all el
31 min read
Check if given Preorder, Inorder and Postorder traversals are of same tree | Set 2
Given Preorder, Inorder and Postorder traversals of some tree. The task is to check if they all are of the same tree.Examples: Input : Inorder -&gt; 4 2 5 1 3 Preorder -&gt; 1 2 4 5 3 Postorder -&gt; 4 5 2 3 1 Output : Yes Explanation : All of the above three traversals are of the same tree. 1 / \ 2 3 / \ 4 5 Input : Inorder -&gt; 4 2 5 1 3 Preorde
11 min read
Check if given Preorder, Inorder and Postorder traversals are of same tree
Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: Input: Inorder -&gt; 4 2 5 1 3 Preorder -&gt; 1 2 4 5 3 Postorder -&gt; 4 5 2 3 1Output: YesExplanation: All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5Input: Inorder -&gt; 4 2 5 1 3 Preorder
20 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
16 min read
Preorder from Inorder and Postorder traversals
Given Inorder and Postorder traversals of a binary tree, print Preorder traversal. Example: Input: Postorder traversal post[] = {4, 5, 2, 6, 3, 1} Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Output: Preorder traversal 1, 2, 4, 5, 3, 6 Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended: Please solve it on “PRA
15 min read
Construct a tree from Inorder and Level order traversals | Set 1
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the two array
11 min read
Construct a tree from Inorder and Level order traversals | Set 2
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Examples: Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the
23 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read