Open In App
Related Articles

Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration.

Examples:

Input: 

 

Output: 
Pre Order:  1 2 4 5 3 6 7 
Post Order:  4 5 2 6 7 3 1 
In Order:    4 2 5 1 6 3 7

Input:  

 

Output: 
Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 
Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 
In Order: 8 12 4 2 9 5 1 6 3 10 7 11 

 

Approach: The iterative solution for this problem is provided in this article. Here this approach is based on the recursion concept.

The idea is to place the recursive calls properly as it is done for each of the inorder, preorder and postorder traversal.

 Follow the steps mentioned below to solve the problem.

  • Create 3 arrays to store the inorder, preorder and postorder traversal.
  • Push the current node in the preorder array and call the recursion function for the left child.
  • Now push the current node in the inorder array and make the recursive call for the right child (right subtree).
  • Visit the current node data in the postorder array before exiting from the current recursion.

Below is the implementation of the above approach.

C++

// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a tree node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
    Node(int val)
    {
        data = val;
        left = NULL;
        right = NULL;
    }
};
 
// Function for traversing tree using
// preorder postorder and inorder method
void PostPreInOrderInOneFlowRecursive(Node* root,
                                      vector<int>& pre,
                                      vector<int>& post,
                                      vector<int>& in)
{
 
    // Return if root is NULL
    if (root == NULL)
        return;
 
    // Pushes the root data into the pre
    // order vector
    pre.push_back(root->data);
 
    // Recursively calls for the left node
    PostPreInOrderInOneFlowRecursive(
        root->left, pre, post, in);
 
    // Pushes node data into the inorder vector
    in.push_back(root->data);
 
    // Recursively calls for the right node
    PostPreInOrderInOneFlowRecursive(
        root->right, pre, post, in);
 
    // Pushes the node data into the Post Order
    // Vector
    post.push_back(root->data);
}
 
// Driver Code
int main()
{
    struct 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->left = new Node(6);
    root->right->right = new Node(7);
    root->left->left->left = new Node(8);
    root->left->left->left->right
        = new Node(12);
    root->left->right->left = new Node(9);
    root->right->right->left = new Node(10);
    root->right->right->right = new Node(11);
 
    // Declaring the vector function to store
    // in, post, pre order values
    vector<int> pre, post, in;
 
    // Calling the function;
    PostPreInOrderInOneFlowRecursive(
        root, pre, post, in);
 
    // Print the values of Pre order, Post order
    // and In order
    cout << "Pre Order : ";
    for (auto i : pre) {
        cout << i << " ";
    }
 
    cout << endl;
    cout << "Post Order : ";
    for (auto i : post) {
        cout << i << " ";
    }
    cout << endl;
    cout << "In Order : ";
    for (auto i : in) {
        cout << i << " ";
    }
    return 0;
}

                    

Java

import java.util.*;
 
// Structure of a tree node
class Node {
    int data;
    Node left, right;
 
    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}
 
class PostPreInOrderInOneFlowRecursive {
    // Function for traversing tree using
    // preorder postorder and inorder method
    static void traverse(Node root, List<Integer> pre, List<Integer> post, List<Integer> in) {
        // Return if root is null
        if (root == null) {
            return;
        }
 
        // Pushes the root data into the pre-order vector
        pre.add(root.data);
 
        // Recursively call for the left node
        traverse(root.left, pre, post, in);
 
        // Pushes node data into the in-order vector
        in.add(root.data);
 
        // Recursively call for the right node
        traverse(root.right, pre, post, in);
 
        // Pushes the node data into the post-order vector
        post.add(root.data);
    }
 
    // Driver code
    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.left = new Node(6);
        root.right.right = new Node(7);
        root.left.left.left = new Node(8);
        root.left.left.left.right = new Node(12);
        root.left.right.left = new Node(9);
        root.right.right.left = new Node(10);
        root.right.right.right = new Node(11);
 
        // Declaring the vector function to store
        // in, post, pre-order values
        List<Integer> pre = new ArrayList<Integer>();
        List<Integer> post = new ArrayList<Integer>();
        List<Integer> in = new ArrayList<Integer>();
 
        // Calling the function
        traverse(root, pre, post, in);
 
        // Print the values of pre-order, post-order,
        // and in-order
        System.out.print("Pre Order : ");
        for (int i : pre) {
            System.out.print(i + " ");
        }
 
        System.out.println();
        System.out.print("Post Order : ");
        for (int i : post) {
            System.out.print(i + " ");
        }
 
        System.out.println();
        System.out.print("In Order : ");
        for (int i : in) {
            System.out.print(i + " ");
        }
    }
}

                    

C#

//C# program to print all the nodes of the binary tree
//in Pre-order, Post-order, and In-order in one iteration.
 
using System;
using System.Collections.Generic;
 
public class GFG{
     
  // Class of a tree node
  class Node {
    public int data;
    public Node left,right;
  
    public Node(int val)
    {
      this.data = val;
      this.left = null;
      this.right = null;
    }
  }
   
  // Function for traversing tree using
  // preorder postorder and inorder method
  static void PostPreInOrderInOneFlowRecursive(Node root,List<int> pre,List<int> post,List<int> inOrder)
  {
  
    // Return if root is null
    if (root == null)
      return;
  
    // Pushes the root data into the pre
    // order vector
    pre.Add(root.data);
  
    // Recursively calls for the left node
    PostPreInOrderInOneFlowRecursive(root.left, pre, post, inOrder);
  
    // Pushes node data into the inorder vector
    inOrder.Add(root.data);
  
    // Recursively calls for the right node
    PostPreInOrderInOneFlowRecursive(root.right, pre, post, inOrder);
  
    // Pushes the node data into the Post Order
    // Vector
    post.Add(root.data);
  }
     
    // Driver Code
    static public void 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.left = new Node(6);
        root.right.right = new Node(7);
        root.left.left.left = new Node(8);
        root.left.left.left.right = new Node(12);
        root.left.right.left = new Node(9);
        root.right.right.left = new Node(10);
        root.right.right.right = new Node(11);
         
        // Declaring the vector function to store
        // in, post, pre order values
        List<int> pre = new List<int>();
        List<int> post = new List<int>();
        List<int> inOrder = new List<int>();
      
        // Calling the function;
        PostPreInOrderInOneFlowRecursive(root, pre, post, inOrder);
      
        // Print the values of Pre order, Post order
        // and In order
        Console.Write("Pre Order : ");
        foreach (var i in pre) {
          Console.Write(i + " ");
        }
      
        Console.Write("\n");
        Console.Write("Post Order : ");
        foreach (var i in post) {
          Console.Write(i + " ");
        }
        Console.Write("\n");
        Console.Write("In Order : ");
        foreach (var i in inOrder) {
          Console.Write(i + " ");
        }
    }
}
//This code is contributed by shruti456rawal

                    

Python3

# Python program for above approach
 
# Structure of a tree node
class Node:
    def __init__(self,val):
        self.data = val
        self.left = None
        self.right = None
 
# Function for traversing tree using
# preorder postorder and inorder method
def PostPreInOrderInOneFlowRecursive(root, pre, post, In):
 
    # Return if root is None
    if (root == None):
        return
 
    # Pushes the root data into the pre
    # order vector
    pre.append(root.data)
 
    # Recursively calls for the left node
    PostPreInOrderInOneFlowRecursive(root.left, pre, post, In)
 
    # Pushes node data into the inorder vector
    In.append(root.data)
 
    # Recursively calls for the right node
    PostPreInOrderInOneFlowRecursive(root.right, pre, post, In)
 
    # Pushes the node data into the Post Order
    # Vector
    post.append(root.data)
 
# Driver Code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.left.right= Node(12)
root.left.right.left = Node(9)
root.right.right.left = Node(10)
root.right.right.right = Node(11)
 
# Declaring the vector function to store 
# in, post, pre order values
pre,post,In = [],[],[]
 
# Calling the function
PostPreInOrderInOneFlowRecursive(root, pre, post, In)
 
# Print the values of Pre order, Post order
# and In order
print("Pre Order : ",end = "")
for i in pre:
    print(i,end = " ")
 
print()
print("Post Order : ",end = "")
for i in post:
    print(i,end = " ")
print()
print("In Order : ",end = "")
for i in In:
    print(i,end = " ")
 
# This code is contributed by shinjanpatra

                    

Javascript

// Define the Node class for creating nodes of the binary tree
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
 
// Function for traversing tree using preorder, postorder and inorder method
function PostPreInOrderInOneFlowRecursive(root, pre, post, inOrder) {
// If root is null, return
if (!root) {
return;
}
// Add root data into pre-order array
pre.push(root.data);
 
// Recursively call for the left node
PostPreInOrderInOneFlowRecursive(root.left, pre, post, inOrder);
 
// Add node data into the in-order array
inOrder.push(root.data);
 
// Recursively call for the right node
PostPreInOrderInOneFlowRecursive(root.right, pre, post, inOrder);
 
// Add node data into the post-order array
post.push(root.data);
}
 
// Create a binary tree
let 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.left = new Node(6);
root.right.right = new Node(7);
root.left.left.left = new Node(8);
root.left.left.left.right = new Node(12);
root.left.right.left = new Node(9);
root.right.right.left = new Node(10);
root.right.right.right = new Node(11);
// Define arrays to store pre-order, post-order and in-order traversal values
let pre = [];
let post = [];
let inOrder = [];
 
// Call the function to traverse the binary tree in pre-order, post-order and in-order and store the values in respective arrays
PostPreInOrderInOneFlowRecursive(root, pre, post, inOrder);
// Print the values of pre-order, post-order and in-order traversal arrays
console.log(`Pre Order: ${pre.join(' ')}`);
console.log(`Post Order: ${post.join(' ')}`);
console.log(`In Order: ${inOrder.join(' ')}`);

                    

Output
Pre Order : 1 2 4 8 12 5 9 3 6 7 10 11 
Post Order : 12 8 4 9 5 2 6 10 11 7 3 1 
In Order : 8 12 4 2 9 5 1 6 3 10 7 11 

Time Complexity: O(N) 
Auxiliary Space: O(N)



Last Updated : 01 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads