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:
Preorder Traversal of Binary Tree
Next article icon

Double Order Traversal of a Binary Tree

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

Given a Binary Tree, the task is to find its Double Order Traversal. Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order: 

  • Visit the Node.
  • Traverse the Left Subtree.
  • Visit the Node.
  • Traverse the Right Subtree.

Examples:

Input:

double-order-traversal-of-a-binary-tree

Output: 1 7 4 4 7 5 5 1 3 6 6 3
Explanation: The root (1) is visited, followed by its left subtree (7), where nodes 4 and 5 are each visited twice before returning to the root and visiting the right subtree (3), which contains node 6.

Input:

double-order-traversal-of-a-binary-tree-2

Output: 1 7 4 4 7 5 5 1 3 3 6 6
Explanation: The root (1) is visited, followed by its left subtree (7), where nodes 4 and 5 are each visited twice before returning to the root and visiting the right subtree (3), where node 6 is visited twice.

Approach:

The idea is to perform Inorder Traversal recursively on the given Binary Tree and store the node value on visiting a vertex and after the recursive call to the left subtree during the traversal. 

Follow the steps below to solve the problem: 

  • Start Inorder traversal from the root. 
  • If the current node does not exist, simply return from it.
  • Otherwise:
    • Store the value of the current node.
    • Recursively traverse the left subtree.
    • Again, store the current node.
    • Recursively traverse the right subtree.
  • Repeat the above steps until all nodes in the tree are visited.

Below is the implementation of the above approach: 

C++
// C++ implementation for printing double order // traversal of a Tree #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;      Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Function to perform double order traversal vector<int> doubleOrderTraversal(Node* root) {     vector<int> result;     if (!root) return result;      // Store node value before traversing      // left subtree     result.push_back(root->data);      // Recursively traverse the left subtree     vector<int> leftSubtree          = doubleOrderTraversal(root->left);        result.insert(result.end(),                leftSubtree.begin(), leftSubtree.end());      // Store node value again after      // traversing left subtree     result.push_back(root->data);      // Recursively traverse the right subtree     vector<int> rightSubtree           = doubleOrderTraversal(root->right);        result.insert(result.end(),                rightSubtree.begin(), rightSubtree.end());      return result; }  int main() {      // Representation of the binary tree     //              1     //           /    \     //         7       3     //       /   \    /     //      4     5  6     Node* root = new Node(1);     root->left = new Node(7);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);       vector<int> result                 = doubleOrderTraversal(root);      for (int num : result) {         cout << num << " ";     }      return 0; } 
Java
// Java implementation for printing double order // traversal of a Tree import java.util.ArrayList;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to perform double order traversal     static ArrayList<Integer>                           doubleOrderTraversal(Node root) {                ArrayList<Integer> result = new ArrayList<>();         if (root == null) return result;          // Store node value before traversing         // left subtree         result.add(root.data);          // Recursively traverse the left subtree         ArrayList<Integer> leftSubtree                      = doubleOrderTraversal(root.left);                result.addAll(leftSubtree);          // Store node value again after         // traversing left subtree         result.add(root.data);          // Recursively traverse the right subtree         ArrayList<Integer> rightSubtree                     = doubleOrderTraversal(root.right);                result.addAll(rightSubtree);          return result;     }      public static void main(String[] args) {          // Representation of the binary tree         //              1         //           /    \         //         7       3         //       /   \    /         //      4     5  6         Node root = new Node(1);         root.left = new Node(7);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);          ArrayList<Integer> result                          = doubleOrderTraversal(root);                for (int num : result) {             System.out.print(num + " ");         }     } } 
Python
# Python implementation for printing double order # traversal of a Tree class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to perform double order traversal def double_order_traversal(root):     result = []     if root is None:         return result      # Store node value before traversing      # left subtree     result.append(root.data)      # Recursively traverse the left subtree     left_subtree = double_order_traversal(root.left)     result.extend(left_subtree)      # Store node value again after      # traversing left subtree     result.append(root.data)      # Recursively traverse the right subtree     right_subtree = double_order_traversal(root.right)     result.extend(right_subtree)      return result   if __name__ == "__main__":      # Representation of the binary tree   #              1   #           /    \   #         7       3   #       /   \    /   #      4     5  6   root = Node(1)   root.left = Node(7)   root.right = Node(3)   root.left.left = Node(4)   root.left.right = Node(5)   root.right.left = Node(6)    result = double_order_traversal(root)   print(" ".join(map(str, result))) 
C#
// C# implementation for printing double order // traversal of a Tree using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to perform double order traversal     static List<int> DoubleOrderTraversal(Node root) {         List<int> result = new List<int>();         if (root == null) return result;          // Store node value before traversing          // left subtree         result.Add(root.data);          // Recursively traverse the left subtree         List<int> leftSubtree                   = DoubleOrderTraversal(root.left);                result.AddRange(leftSubtree);          // Store node value again after          // traversing left subtree         result.Add(root.data);          // Recursively traverse the right subtree         List<int> rightSubtree                   = DoubleOrderTraversal(root.right);                result.AddRange(rightSubtree);          return result;     }      static void Main(string[] args) {          // Representation of the binary tree         //              1         //           /    \         //         7       3         //       /   \    /         //      4     5  6         Node root = new Node(1);         root.left = new Node(7);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);          List<int> result                           = DoubleOrderTraversal(root);                 foreach (int num in result) {             Console.Write(num + " ");         }     } } 
JavaScript
// JavaScript implementation for printing double order // traversal of a Tree class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to perform double order traversal function doubleOrderTraversal(root) {     const result = [];     if (root === null) return result;      // Store node value before traversing      // left subtree     result.push(root.data);      // Recursively traverse the left subtree     const leftSubtree = doubleOrderTraversal(root.left);     result.push(...leftSubtree);      // Store node value again after      // traversing left subtree     result.push(root.data);      // Recursively traverse the right subtree     const rightSubtree = doubleOrderTraversal(root.right);     result.push(...rightSubtree);      return result; }   // Representation of the binary tree //              1 //           /    \ //         7       3 //       /   \    / //      4     5  6 const root = new Node(1); root.left = new Node(7); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6);  const result = doubleOrderTraversal(root); console.log(result.join(" ")); 

Output
1 7 4 4 7 5 5 1 3 6 6 3 

Time complexity: O(n), as each node is visited twice, where n is the number of nodes in the tree.
Auxiliary Space: O(h), due to recursion, where h is the tree’s height.



Next Article
Preorder Traversal of Binary Tree
author
chitrankmishra
Improve
Article Tags :
  • Data Structures
  • DSA
  • Recursion
  • Tree
  • Binary Tree
  • Inorder Traversal
Practice Tags :
  • Data Structures
  • Recursion
  • Tree

Similar Reads

  • Mix Order Traversal of a Binary Tree
    Given a Binary Tree consisting of N nodes, the task is to print its Mix Order Traversal. Mix Order Traversal is a tree traversal technique, which involves any two of the existing traversal techniques like Inorder, Preorder and Postorder Traversal. Any two of them can be performed or alternate levels
    13 min read
  • Boundary Level order traversal of a Binary Tree
    Given a Binary Tree, the task is to print all levels of this tree in Boundary Level order traversal. Boundary Level order traversal: In this traversal, the first element of the level (starting boundary) is printed first, followed by last element (ending boundary). Then the process is repeated for th
    11 min read
  • Middle To Up-Down Order traversal of a Binary Tree
    Given a binary tree, the task is to traverse this binary tree from the middle to the up-down order. In Middle to up-down order traversal, the following steps are performed: First, print the middle level of the tree.Then, print the elements at one level above the middle level of the tree.Then, print
    15+ min read
  • Preorder Traversal of Binary Tree
    Preorder traversal is a tree traversal method that follows the Root-Left-Right order: The root node of the subtree is visited first.Next, the left subtree is recursively traversed.Finally, the right subtree is recursively traversed.How does Preorder Traversal work?Key Properties: Used in expression
    5 min read
  • Triple Order Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its Triple Order Traversal. Triple Order Traversal is a tree traversal technique in which every node is traversed thrice in the following order: Visit the root nodeTraverse the left subtreeVisit the root nodeTraverse the right subtreeVisit the root node.Examp
    7 min read
  • Postorder Traversal of Binary Tree
    Postorder traversal is a tree traversal method that follows the Left-Right-Root order: The left subtree is visited first.The right subtree is visited next.The root node is processed last.How does Postorder Traversal work? Key Properties:It is used for tree deletion because subtrees are deleted befor
    5 min read
  • Sideways traversal of a Complete Binary Tree
    Given a Complete Binary Tree, the task is to print the elements in the following pattern. Let's consider the tree to be: The tree is traversed in the following way: The output for the above tree is: 1 3 7 11 10 9 8 4 5 6 2 Approach: The idea is to use the modified breadth first search function to st
    15+ min read
  • Specific Level Order Traversal of Binary Tree
    Given a Binary Tree, the task is to perform a Specific Level Order Traversal of the tree such that at each level print 1st element then the last element, then 2nd element and 2nd last element, until all elements of that level are printed and so on. Examples: Input: Output: 5 3 7 2 8 4 6 9 0 5 1 Expl
    8 min read
  • Diagonal Traversal of Binary Tree
    Given a Binary Tree, the task is to print the diagonal traversal of the binary tree.Note: If the diagonal element are present in two different subtrees, then left subtree diagonal element should be taken first and then right subtree. Example: Input: Output: 8 10 14 3 6 7 13 1 4Explanation: The above
    7 min read
  • Find n-th node in Preorder traversal of a Binary Tree
    Given a binary tree. The task is to find the n-th node of preorder traversal. Examples: Input: Output: 50Explanation: Preorder Traversal is: 10 20 40 50 30 and value of 4th node is 50.Input: Output : 3Explanation: Preorder Traversal is: 7 2 3 8 5 and value of 3rd node is 3. Table of Content [Naive A
    11 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