Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Double Order Traversal of a 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
Double Order Traversal of a Binary Tree

C

chitrankmishra
Improve
Article Tags :
  • Tree
  • Recursion
  • Data Structures
  • DSA
  • Inorder Traversal
  • Binary Tree
Practice Tags :
  • Data Structures
  • Recursion
  • Tree

Similar Reads

    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 t
    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
    Inorder Traversal of Binary Tree
    Inorder traversal is a depth-first traversal method that follows this sequence:Left subtree is visited first.Root node is processed next.Right subtree is visited last.How does Inorder Traversal work?Key Properties:If applied to a Binary Search Tree (BST), it returns elements in sorted order.Ensures
    5 min read
    Boundary Traversal of binary tree
    Given a binary tree, the task is to find the boundary nodes of the binary tree Anti-Clockwise starting from the root.The boundary includes:left boundary (nodes on left excluding leaf nodes)leaves (consist of only the leaf nodes)right boundary (nodes on right excluding leaf nodes)The left boundary is
    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