Related Articles

Related Articles

Print the middle nodes of each level of a Binary Tree
  • Difficulty Level : Hard
  • Last Updated : 11 Dec, 2020

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

1
2 3
5 10
11 6
7 9

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :