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
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Print nodes in top view of Binary Tree | Set 2
Next article icon

Inorder Tree Traversal of Binary Tree in C++

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A binary tree is a non-linear hierarchical data structure in which each node has at most two children known as the left child and the right child. As the binary tree has non-linear structure it can be traversed in multiple ways one such way is in-order traversal which is a depth first (DFS) traversal technique that follows the Left-Root-Right pattern.

In this article, we will learn how to implement in-order binary tree traversal in C++ and analyze its space and time complexity.

Inorder Traversal of Binary Tree in C++

In-order traversal is a DFS tree traversal technique for the binary tree where the left subtree is traversed first followed by the root node and the right subtree at the end.

inorder-traversal
Inorder Traversal
  1. Traverse the left subtree.
  2. Visit the root node.
  3. Traverse the right subtree.

Consider the following example:

inordertraversalBinaryTree
Inorder Traversal Example

For inorder traversal of the above tree:

  1. Start with the leftmost node, which is 4.
  2. Move up to its parent, which is 2.
  3. Visit the right child of 2, which is 5.
  4. Move up to the root node, which is 1.
  5. Finally, visit the right subtree, which is node 3.

So, the inorder traversal of the tree is: 4, 2, 5, 1, 3.

Algorithm for Inorder Binary Tree Traversal

Below is the algorithm of the inorder binary tree traversal:

inorder(TreeNode* root) {
if (root == NULL)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}

C++ Program For Inorder Traversal of a Binary Tree

The following program illustrates how to implement the inorder traversal of a binary tree in C++.

C++
// C++ Program for inorder traversal of a Binary Tree  #include <iostream> using namespace std;  //  BINARY TREE IMPLEMENTATION  // Class definition for a binary tree node class Node { public:     int data;     Node* left;     Node* right;      // Constructor to create a new node     Node(int data)     {         this->data = data;         this->left = nullptr;         this->right = nullptr;     } };  // Class definition for a binary tree class BinaryTree { public:     Node* root;      // Constructor to initialize the root     BinaryTree() { root = nullptr; }      // INORDER TRAVERSAL     // Function to perform inorder traversal     void inorderTraversal(Node* node)     {         if (node != nullptr) {              inorderTraversal(node->left);             cout << node->data << " ";             inorderTraversal(node->right);         }     } };  int main() {     // Initialize a binary tree     BinaryTree btree;     btree.root = new Node(1);     btree.root->left = new Node(2);     btree.root->right = new Node(3);     btree.root->left->left = new Node(4);     btree.root->left->right = new Node(5);      // Perform the inorder traversal     cout << "The inorder traversal of the binary tree is:"          << endl;     btree.inorderTraversal(btree.root);     cout << endl;      return 0; } 

Output
The inorder traversal of the binary tree is: 4 2 5 1 3  

Time Complexity: O(N), here N denotes the total number of nodes in the binary tree because we visit each node exactly once.
Auxiliary Space: O(1), if the recursive stack space is not considered. If the stack space is considered then O(log N), for a balanced tree and O(N) for a skewed tree.

Refer to this article for more detailed time and space complexity analysis.

Applications of Inorder Traversal

Following are some of the common applications of inorder traversal:

  • Copying and Cloning: In-order traversal can be used to create a copy of the binary tree or to clone it by visiting each node in the correct order.
  • Sorted Elements: The inorder traversal of a binary search tree always returns the elements in non-decreasing sorted order.
  • Expression Trees: Inorder traversal is used to retrieve the infix expression from an expression tree, which is important in expression evaluation and compiler design.
  • Counting Nodes in a Range: It can be used to count the number of nodes within a certain range in a BST by skipping unnecessary subtrees.

Related Articles:

You can go through these articles to improve your understanding about the inorder traverals:

  • Types of Tree Traversals
  • Iterative inorder traversal
  • Construct binary tree from inorder and inorder traversal
  • Morris traversal for inorder traversal of tree

Next Article
Print nodes in top view of Binary Tree | Set 2

G

girishp5g4
Improve
Article Tags :
  • C++ Programs
  • C++
  • C-DSA
Practice Tags :
  • CPP

Similar Reads

  • Clockwise Spiral Traversal of Binary Tree
    Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree. For the above binary tree, the circular clockwise spiral order traversal will be 1, 4, 5, 6, 7, 2, 3. Examples: Input : 10 / \ 12 13 / \ 14 15 / \ / \ 21 22 23 24 Output : 10, 24, 23, 22
    15+ min read
  • Iterative Boundary Traversal of Complete Binary tree
    Given a complete binary tree, the task is to traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root. Example: Input: Output: 1 2 4 5 6 7 3 Input: Output: 18 15 40 50 100 20 30 Approach: Traverse left-most nodes of the tree from top to down. (Left boun
    9 min read
  • Print nodes in top view of Binary Tree | Set 2
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
    14 min read
  • Clockwise Spiral Traversal of Binary Tree | Set - 2
    Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output :1 9 8 7 2 3 6 5 4 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output :20 14 10 8 22 25 4 3 5 We have already discussed Clock
    11 min read
  • Binary Search Tree in C++
    A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and el
    10 min read
  • Deletion of a given node K in a Binary Tree using Level Order Traversal
    Given a binary tree and a node K, the task is to delete the node K from it by making sure that tree shrinks from the bottom (i.e. the deleted node is replaced by bottom-most and rightmost node) using Level Order Traversal. Examples: Input: K = 8, Tree = Output: Explanation: Please Refer below for ex
    13 min read
  • Zig-Zag traversal of a Binary Tree using Recursion
    Given a binary tree, the task is to find the zigzag level order traversal of the tree. In zig zag traversal starting from the first level go from left to right for odd-numbered levels and right to left for even-numbered levels. Approach: The zigzag traversal of a binary tree involves traversing the
    11 min read
  • How to Read Binary Search Tree from File in C++?
    A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it effic
    4 min read
  • Sum of the mirror image nodes of a complete binary tree in an inorder way
    Given a complete binary tree, the task is to find the sum of mirror image nodes in an inorder way i.e. find the inorder traversal of the left sub-tree and for every node traversed, add the value of its mirror node to the current node's value. Examples: Input: Output: 20 51 19 10 Inorder traversal of
    6 min read
  • Connect all nodes to their Left Neighbors in a Binary Tree
    Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbor at the same level using this extra pointer.Examples: Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL
    10 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