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 the nodes of Binary Tree having a grandchild
Next article icon

Print the middle nodes of each level of a Binary Tree

Last Updated : 22 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree, the task is to print the middle nodes of each level of a binary tree. Considering M to be the number of nodes at any level, print (M/2)th node if M is odd. Otherwise, print (M/2)th node and ((M/2) + 1)th node.

Examples:

Input: Below is the given Tree: 

Output:
1
2 3
5 10
11 6
7 9
Explanation:
The mid nodes of each level is:
Level 0 – 1  
Level 1 – 2 and 3
Level 2 – 5 and 10
Level 3 – 11 and 6
Level 4 – 7 and 9

Input: Below is the given Tree: 

Output:
1
2 3
5
8 9
11
12 13
15 14
Explanation:
The mid nodes of each level is:
Level 0 – 1
Level 1 – 2 and 3
Level 2 – 5
Level 3 – 8 and 9
Level 4 – 11
Level 5 – 12 and 13
Level 6 – 15 and 14

Approach: The idea is to perform the DFS Traversal on the given Tree and store all the nodes for each level in a map of vectors. Now traverse the Map and print the middle nodes accordingly. Below are the steps:

  1. Initialize a map of vectors M to stores all the nodes corresponding to each level in a vector.
  2. Perform DFS Traversal on the given Tree starting with level 0 and recursively call the left and right subtree with increment in the level by 1.
  3. Stores all the nodes in the above DFS Traversal corresponding to each level as M[level].push_back(root->data).
  4. Now, traverse the Map M and for each level do the following:
    • Find the size(say S) of the vector(say A) associated with each level in map M.
    • If S is odd then simply print the value of A[(S – 1)/2] as the middle (S/2)th node.
    • Else print the value of A[(S – 1)/2] and A[(S – 1)/2 + 1] as the middle (S/2)th and ((S/2) + 1)th node.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure Node of Binary Tree
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Function to create a new node
struct node* newnode(int d)
{
    struct node* temp
        = (struct node*)malloc(
            sizeof(struct node));
    temp->data = d;
    temp->left = NULL;
    temp->right = NULL;
 
    // Return the created node
    return temp;
}
 
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
void dfs(node* root, int l,
         map<int, vector<int> >& M)
{
    // Base Case
    if (root == NULL)
        return;
 
    // Push the current level node
    M[l].push_back(root->data);
 
    // Left Recursion
    dfs(root->left, l + 1, M);
 
    // Right Recursion
    dfs(root->right, l + 1, M);
}
 
// Function that print all the middle
// nodes for each level in Binary Tree
void printMidNodes(node* root)
{
 
    // Stores all node in each level
    map<int, vector<int> > M;
 
    // Perform DFS traversal
    dfs(root, 0, M);
 
    // Traverse the map M
    for (auto& it : M) {
 
        // Get the size of vector
        int size = it.second.size();
 
        // For odd number of elements
        if (size & 1) {
 
            // Print (M/2)th Element
            cout << it.second[(size - 1) / 2]
                 << endl;
        }
 
        // Otherwise
        else {
 
            // Print (M/2)th and
            // (M/2 + 1)th Element
            cout << it.second[(size - 1) / 2]
                 << ' '
                 << it.second[(size - 1) / 2 + 1]
                 << endl;
        }
    }
}
 
// Driver Code
int main()
{
    /*
    Binary tree shown below is:
  
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
  
  
    */
 
    // Given Tree
    struct node* root = newnode(1);
    root->left = newnode(2);
    root->right = newnode(3);
    root->left->left = newnode(4);
    root->left->right = newnode(5);
    root->left->right->left = newnode(11);
    root->left->right->right = newnode(6);
    root->left->right->right->left = newnode(7);
    root->left->right->right->right = newnode(9);
    root->right->left = newnode(10);
    root->right->right = newnode(8);
 
    // Function Call
    printMidNodes(root);
 
    return 0;
}
 
 

Java




// Java program for
// the above approach
import java.util.*;
class GFG{
   
static Map<Integer, Vector<Integer> > M;
 
// Structure Node of
// Binary Tree
static class node
{
  int data;
  node left;
  node right;
  public node() {}
  public node(int data,
              node left,
              node right)
  {
    super();
    this.data = data;
    this.left = left;
    this.right = right;
  }
};
 
// Function to create a new node
static node newnode(int d)
{
  node temp = new node();
  temp.data = d;
  temp.left = null;
  temp.right = null;
 
  // Return the created node
  return temp;
}
 
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
static void dfs(node root, int l)
{
  // Base Case
  if (root == null)
    return;
 
  // Push the current level node
  if(!M.containsKey(l))
  {
    Vector<Integer> temp = new Vector<Integer>();
    temp.add(root.data);
    M.put(l, temp);
  }
  else
    M.get(l).add(root.data);
 
  // Left Recursion
  dfs(root.left, l + 1);
 
  // Right Recursion
  dfs(root.right, l + 1);
}
 
// Function that print all the middle
// nodes for each level in Binary Tree
static void printMidNodes(node root)
{
  // Stores all node in each level
  M = new HashMap<Integer,
          Vector<Integer> >();
   
  // Perform DFS traversal
  dfs(root, 0);
 
  // Traverse the map M
  for (Map.Entry<Integer,
       Vector<Integer>> it : M.entrySet())
  {
    // Get the size of vector
    int size = it.getValue().size();
 
    // For odd number of elements
    if (size % 2 == 1)
    {
      // Print (M/2)th Element
      System.out.print(it.getValue().get((size - 1) / 2) + "\n");
    }
 
    // Otherwise
    else
    {
      // Print (M/2)th and
      // (M/2 + 1)th Element
      System.out.print(it.getValue().get((size - 1) / 2) + " " +
                       it.getValue().get(((size - 1) / 2) + 1) + "\n");
    }
  }
}
 
// Driver Code
public static void main(String[] args)
{
  /*
    Binary tree shown below is:
 
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
 
 
    */
 
  // Given Tree
  node root = newnode(1);
  root.left = newnode(2);
  root.right = newnode(3);
  root.left.left = newnode(4);
  root.left.right = newnode(5);
  root.left.right.left = newnode(11);
  root.left.right.right = newnode(6);
  root.left.right.right.left = newnode(7);
  root.left.right.right.right = newnode(9);
  root.right.left = newnode(10);
  root.right.right = newnode(8);
 
  // Function Call
  printMidNodes(root);
}
}
 
//This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program for the above approach
  
# Structure Node of Binary Tree
class node:
 
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# Function to create a new node
def newnode(d):
 
    temp = node(d)
  
    # Return the created node
    return temp
  
# Function that performs the DFS
# traversal on Tree to store all the
# nodes at each level in map M
def dfs(root, l, M):
 
    # Base Case
    if (root == None):
        return
  
    # Push the current level node
    if l not in M:
        M[l] = []
         
    M[l].append(root.data)
  
    # Left Recursion
    dfs(root.left, l + 1, M)
  
    # Right Recursion
    dfs(root.right, l + 1, M)
 
# Function that print all the middle
# nodes for each level in Binary Tree
def printMidNodes(root):
  
    # Stores all node in each level
    M = dict()
  
    # Perform DFS traversal
    dfs(root, 0, M)
  
    # Traverse the map M
    for it in M.values():
  
        # Get the size of vector
        size = len(it)
  
        # For odd number of elements
        if (size & 1):
  
            # Print (M/2)th Element
            print(it[(size - 1) // 2])
  
        # Otherwise
        else:
  
            # Print (M/2)th and
            # (M/2 + 1)th Element
            print(str(it[(size - 1) // 2]) + ' ' +
                  str(it[(size - 1) // 2 + 1]))
  
# Driver Code
if __name__=="__main__":
 
    '''
    Binary tree shown below is:
            1
          /   \
        2      3
      /   \   /  \
     4     5 10   8
          / \
         11  6
            / \
           7   9
    '''
     
    # Given Tree
    root = newnode(1)
    root.left = newnode(2)
    root.right = newnode(3)
    root.left.left = newnode(4)
    root.left.right = newnode(5)
    root.left.right.left = newnode(11)
    root.left.right.right = newnode(6)
    root.left.right.right.left = newnode(7)
    root.left.right.right.right = newnode(9)
    root.right.left = newnode(10)
    root.right.right = newnode(8)
  
    # Function Call
    printMidNodes(root)
  
# This code is contributed by rutvik_56
 
 

C#




// C# program for
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
    
static Dictionary<int,ArrayList> M;
  
// Structure Node of
// Binary Tree
class node
{
  public int data;
  public node left;
  public node right;
  public node(int data,
              node left,
              node right)
  {
    this.data = data;
    this.left = left;
    this.right = right;
  }
};
  
// Function to create a new node
static node newnode(int d)
{
  node temp = new node(d, null, null);
  
  // Return the created node
  return temp;
}
  
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
static void dfs(node root, int l)
{
  // Base Case
  if (root == null)
    return;
  
  // Push the current level node
  if(!M.ContainsKey(l))
  {
    ArrayList temp = new ArrayList();
    temp.Add(root.data);
    M[l] = temp;
  }
  else
    M[l].Add(root.data);
  
  // Left Recursion
  dfs(root.left, l + 1);
  
  // Right Recursion
  dfs(root.right, l + 1);
}
  
// Function that print all the middle
// nodes for each level in Binary Tree
static void printMidNodes(node root)
{
  // Stores all node in each level
  M = new Dictionary<int, ArrayList>();
    
  // Perform DFS traversal
  dfs(root, 0);
  
  // Traverse the map M
  foreach (KeyValuePair<int,ArrayList> it in M)
  {
    // Get the size of vector
    int size = it.Value.Count;
  
    // For odd number of elements
    if (size % 2 == 1)
    {
      // Print (M/2)th Element
      Console.Write(it.Value[(size - 1) / 2] + "\n");
    }
  
    // Otherwise
    else
    {
       
      // Print (M/2)th and
      // (M/2 + 1)th Element
      Console.Write(it.Value[(size - 1) / 2] + " " +
                       it.Value[((size - 1) / 2) + 1] + "\n");
    }
  }
}
  
// Driver Code
public static void Main(string[] args)
{
  /*
    Binary tree shown below is:
  
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
  
  
    */
  
  // Given Tree
  node root = newnode(1);
  root.left = newnode(2);
  root.right = newnode(3);
  root.left.left = newnode(4);
  root.left.right = newnode(5);
  root.left.right.left = newnode(11);
  root.left.right.right = newnode(6);
  root.left.right.right.left = newnode(7);
  root.left.right.right.right = newnode(9);
  root.right.left = newnode(10);
  root.right.right = newnode(8);
  
  // Function Call
  printMidNodes(root);
}
}
 
// This code is contributed by pratham76
 
 

Javascript




<script>
 
// Javascript program for
// the above approach
var M = new Map();
  
// Structure Node of
// Binary Tree
class node
{
    constructor(data, left, right)
    {
        this.data = data;
        this.left = left;
        this.right = right;
    }
};
  
// Function to create a new node
function newnode(d)
{
    var temp = new node(d, null, null);
     
    // Return the created node
    return temp;
}
  
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
function dfs(root, l)
{
     
    // Base Case
    if (root == null)
        return;
     
    // Push the current level node
    if (!M.has(l))
    {
        var temp = [];
        temp.push(root.data);
        M.set(l, temp);
    }
    else
    {
        var temp = M.get(l);
        temp.push(root.data);
        M.set(l, temp);
    }
     
    // Left Recursion
    dfs(root.left, l + 1);
     
    // Right Recursion
    dfs(root.right, l + 1);
}
  
// Function that print all the middle
// nodes for each level in Binary Tree
function printMidNodes(root)
{
     
    // Stores all node in each level
    M = new Map();
     
    // Perform DFS traversal
    dfs(root, 0);
     
    // Traverse the map M
    M.forEach((value,key) => {
     
        // Get the size of vector
        var size = value.length;
         
        // For odd number of elements
        if (size % 2 == 1)
        {
            // Print (M/2)th Element
            document.write(value[parseInt(
                (size - 1) / 2)] + "<br>");
        }
         
        // Otherwise
        else
        {
             
            // Print (M/2)th and
            // (M/2 + 1)th Element
            document.write(value[parseInt((size - 1) / 2)] + " " +
                          value[parseInt(((size - 1) / 2) + 1)] + "<br>");
        }
    });
}
  
// Driver Code
/*
  Binary tree shown below is:
 
          1
        /   \
      2      3
    /   \   /  \
   4     5 10   8
        / \
       11  6
          / \
         7   9
 
 
  */
 
// Given Tree
var root = newnode(1);
root.left = newnode(2);
root.right = newnode(3);
root.left.left = newnode(4);
root.left.right = newnode(5);
root.left.right.left = newnode(11);
root.left.right.right = newnode(6);
root.left.right.right.left = newnode(7);
root.left.right.right.right = newnode(9);
root.right.left = newnode(10);
root.right.right = newnode(8);
 
// Function Call
printMidNodes(root);
 
// This code is contributed by noob2000
 
</script>
 
 
Output: 
1 2 3 5 10 11 6 7 9

 

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



Next Article
Print the nodes of Binary Tree having a grandchild
author
sunilkannur98
Improve
Article Tags :
  • DSA
  • Recursion
  • Searching
  • Tree
  • cpp-map
  • cpp-vector
  • DFS
  • Tree Traversals
Practice Tags :
  • DFS
  • Recursion
  • Searching
  • Tree

Similar Reads

  • Print all Nodes of given Binary Tree at the Kth Level
    Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
    5 min read
  • Print the nodes at odd levels of a tree
    Given a binary tree, print nodes of odd level in any order. Root is considered at level 1. For example consider the following tree 1 / \ 2 3 / \ \ 4 5 6 / \ / 7 8 9 Output 1 4 5 6Recommended PracticeNodes at Odd LevelsTry It! Method 1 (Recursive): The idea is to pass initial level as odd and switch
    9 min read
  • Print the nodes of Binary Tree having a grandchild
    Given a Binary Tree, the task is to print the nodes that have grandchildren. Examples: Input: Output: 20 8 Explanation: 20 and 8 are the grandparents of 4, 12 and 10, 14. Input: Output: 1 Explanation: 1 is the grandparent of 4, 5. Approach: The idea uses Recursion. Below are the steps: Traverse the
    8 min read
  • Print all nodes except rightmost node of every level of the Binary Tree
    Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3
    7 min read
  • Print Levels of all nodes in a Binary Tree
    Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
    7 min read
  • Print and remove leaf nodes of given Binary Tree on each iteration
    Given a binary tree, the task is to: Print all the leaf nodes and then delete them all. Repeat this process till the tree becomes empty. Examples: Input: 1 /. \ 2 3 / \ 4 5 Output: Iteration 1: 4 5 3Iteration 2: 2Iteration 3: 1Explanation: The leaf nodes initially were 4, 5 and 3.When those were del
    7 min read
  • Print the number of set bits in each node of a Binary Tree
    Given a Binary Tree. The task is to print the number of set bits in each of the nodes in the Binary Tree. The idea is to traverse the given binary tree using any tree traversal method, and for each node calculate the number of set bits and print it. Note: One can also use the __builtin_popcount() fu
    6 min read
  • Print extreme nodes of each level of Binary Tree in alternate order
    Given a binary tree, print nodes of extreme corners of each level but in alternate order.Example: For above tree, the output can be 1 2 7 8 31 - print rightmost node of 1st level - print leftmost node of 2nd level - print rightmost node of 3rd level - print leftmost node of 4th level - print rightmo
    10 min read
  • Print all the leaf nodes of Binary Heap
    Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 5 6 7 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 Leaf nodes of the Binary Heap are: 4 5 6 7 Input: arr[] =
    7 min read
  • Print all even nodes of Binary Search Tree
    Given a binary search tree. The task is to print all even nodes of the binary search tree. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 2 4 6 8 Input : 14 / \ 12 17 / \ / \ 8 13 16 19 Output : 8 12 14 16 Approach: Traverse the Binary Search tree and check if current node's value is even. If
    8 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