Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print Postorder traversal from given Inorder and Preorder traversals
Next article icon

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

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)


Next Article
Print Postorder traversal from given Inorder and Preorder traversals

T

thilakreddy
Improve
Article Tags :
  • Tree
  • DSA
Practice Tags :
  • Tree

Similar Reads

  • Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
    Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5
    13 min read
  • Post Order Traversal of Binary Tree in O(N) using O(1) space
    Prerequisites:- Morris Inorder Traversal, Tree Traversals (Inorder, Preorder and Postorder)Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9Output: 8 9 4 5 2 6 7 3 1Input: 5 / \ 7 3 / \ / \ 4 1
    15+ 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, the task is 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 genera
    9 min read
  • Print Postorder traversal from given Inorder and Preorder traversals
    Given two arrays represent Inorder and Preorder traversals of a binary tree, the task is to find the Postorder traversal. Example: Input: in[] = [4, 2, 5, 1, 3, 6] pre[] = [1, 2, 4, 5, 3, 6]Output: 4 5 2 6 3 1Explanation: Traversals in the above example represents following tree: A naive method is t
    11 min read
  • Level order traversal of Binary Tree using Morris Traversal
    Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two ob
    11 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:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output:
    11 min read
  • Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
    Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both t
    11 min read
  • Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
    Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965};Output : 290 530 965Explanation: Below is the representation of BST using preorder array. Approach: To i
    8 min read
  • Modify a binary tree to get preorder traversal using right pointers only
    Given a binary tree. The task is to modify it in such a way that after modification preorder traversal of it can get only with the right pointers. During modification, we can use right as well as left pointers. Examples: Input : Output : Explanation: The preorder traversal of given binary tree is 10
    12 min read
  • Postorder traversal of Binary Tree without recursion and without stack
    Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The app
    15 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