Open In App

Print the nodes corresponding to the level value for each level of a Binary Tree

Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree, the task for each level L is to print the Lth node of the tree. If the Lth node is not present for any level, print -1.

Note: Consider the root node to be at the level 1 of the binary tree.

Examples:

Input: Below is the given Tree: Output:
Level 1: 1
Level 2: 3 
Level 3: 6
Level 4: 11
Explanation:
For the first level, the 1st node is 1. 
For the second level, the 2nd node is 3.
For the third level, the 3rd node is 6.
For the fourth level, the 4th node is 11.

Input: Below is the given Tree: Output:
Level 1: 1
Level 2: 3
Level 3: 6
Level 4: -1
Explanation:
For the first level, the 1st node is 1. 
For the second level, the 2nd node is 3.
For the third level, the 3rd node is 6.
For the fourth level, the 4th node is not available. Hence, print -1.

Approach: To solve this problem the idea is to use Multimap. Follow the steps below to solve the problem:

  1. Traverse the given tree and store the level of each node and the node’s value in the Multimap.
  2. The levels of the nodes are considered as the key of the multimap. Keep track of the maximum level of the Binary Tree(say L).
  3. Now, iterate the Multimap over the range [1, L] and perform the following operations:
    • For each level L, traverse till the Lth node of that level check if it exists or not. If found to be existing, print the value of that node.
    • Otherwise, print “-1” and proceed to the next level.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Stores the level of the node and
// its value at the max level of BT
multimap<int, int> m;
 
// Stores the maximum level
int maxlevel = 0;
 
// Structure of Binary Tree
struct node {
 
    int data;
    struct node* left;
    struct node* right;
};
 
// Function to insert the node in
// the Binary Tree
struct node* newnode(int d)
{
    struct node* temp
        = (struct node*)malloc(
            sizeof(struct node));
    temp->data = d;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Function to find node of Nth level
void findNode(struct node* root, int level)
{
    // If root exists
    if (root) {
 
        // Traverse left subtree
        findNode(root->left, level + 1);
 
        // Insert the node's level and
        // its value into the multimap
        m.insert({ level, root->data });
 
        // Update the maximum level
        maxlevel = max(maxlevel, level);
 
        // Traverse the right subtree
        findNode(root->right, level + 1);
    }
}
 
// Function to print the L-th node at
// L-th level of the Binary Tree
void printNode(struct node* root, int level)
{
    // Function Call
    findNode(root, level);
 
    // Iterator for traversing map
    multimap<int, int>::iterator it;
 
    // Iterate all the levels
    for (int i = 0; i <= maxlevel; i++) {
 
        // Print the current level
        cout << "Level " << i + 1 << ": ";
 
        it = m.find(i);
        int flag = 0;
 
        // Iterate upto i-th node of the
        // i-th level
        for (int j = 0; j < i; j++) {
 
            it++;
 
            // If end of the level
            // is reached
            if (it == m.end()) {
                flag = 1;
                break;
            }
        }
 
        // If i-th node does not exist
        // in the i-th level
        if (flag == 1 || it->first != i) {
            cout << "-1" << endl;
        }
 
        // Otherwise
        else {
 
            // Print the i-th node
            cout << it->second << endl;
        }
    }
}
 
// Driver code
int main()
{
    // Construct the Binary 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(12);
    root->left->left->left = newnode(9);
    root->left->left->right = newnode(10);
    root->right->left = newnode(6);
    root->right->right = newnode(7);
    root->right->right->left = newnode(13);
    root->right->right->right = newnode(14);
 
    // Function Call
    printNode(root, 0);
}


Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
     
    // Stores the level of the node and
    // its value at the max level of BT
    static HashMap<Integer,ArrayList<Integer>> m = new HashMap<>();
     
    // Stores the maximum level
    static int maxlevel = 0;
     
    // Structure of a BST node
    static class node {
        int data;
        node left;
        node right;
    }
     
    // Utility function to create a new BST node
    static node newnode(int d)
    {
        node temp = new node();
        temp.left = null;
        temp.right = null;
        temp.data = d;
        return temp;
    }
     
    // Function to find node of Nth level
    static void findNode(node root, int level)
    {
        // If root exists
        if (root!=null) {
       
            // Traverse left subtree
            findNode(root.left, level + 1);
       
            // Insert the node's level and
            // its value into the multimap
            if(m.get(level)==null){
                m.put(level,new ArrayList<Integer>());
            }
            m.get(level).add(root.data);
       
            // Update the maximum level
            maxlevel = Math.max(maxlevel, level);
       
            // Traverse the right subtree
            findNode(root.right, level + 1);
        }
    }
       
    // Function to print the L-th node at
    // L-th level of the Binary Tree
    static void printNode(node root, int level)
    {
        // Function Call
        findNode(root, level);
       
        // Iterate all the levels
        for (int i = 0; i <= maxlevel; i++) {
       
            // Print the current level
            System.out.print("Level " + (i + 1) + ": ");
       
            List<Integer> it = m.get(i);
            int flag = 0;
       
            // Iterate upto i-th node of the
            // i-th level
            if(it.size()<i){
                // If end of the level
                // is reached
                flag=1;
                System.out.print("-1\n");
            }else{
                // Print the i-th node
                System.out.print(it.get(i)+"\n");
            }
        }
    }
     
    //Driver Code
    public static void main (String[] args) {
        // Construct the Binary 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(12);
        root.left.left.left = newnode(9);
        root.left.left.right = newnode(10);
        root.right.left = newnode(6);
        root.right.right = newnode(7);
        root.right.right.left = newnode(13);
        root.right.right.right = newnode(14);
       
        // Function Call
        printNode(root, 0);
    }
}
 
// This code is contributed by shruti456rawal


Python3




# Python3 program for the above approach
from collections import defaultdict
 
# Stores the level of the node and
# its value at the max level of BT
m = defaultdict(list)
 
# Stores the maximum level
maxlevel = 0
 
# Structure of Binary Tree
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to insert the node in
# the Binary Tree
def newnode(d):
    temp = Node(d)
    return temp
 
# Function to find node of Nth level
def findNode(root, level):
    # If root exists
    if root:
        # Traverse left subtree
        findNode(root.left, level + 1)
 
        # Insert the node's level and
        # its value into the multimap
        m[level].append(root.data)
 
        # Update the maximum level
        global maxlevel
        maxlevel = max(maxlevel, level)
 
        # Traverse the right subtree
        findNode(root.right, level + 1)
 
# Function to print the L-th node at
# L-th level of the Binary Tree
def printNode(root, level):
    # Function Call
    findNode(root, level)
 
    # Iterate all the levels
    for i in range(maxlevel+1):
        # Print the current level
        print("Level {}: ".format(i + 1), end="")
 
        # If i-th node does not exist
        # in the i-th level
        if i not in m:
            print("-1")
        else:
            # Print the i-th node
            print(m[i][i])
 
# Driver code
if __name__ == "__main__":
    # Construct the Binary 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(12)
    root.left.left.left = newnode(9)
    root.left.left.right = newnode(10)
    root.right.left = newnode(6)
    root.right.right = newnode(7)
    root.right.right.left = newnode(13)
    root.right.right.right = newnode(14)
 
    # Function Call
    printNode(root, 0)
 
# This code is contributed by Potta Lokesh


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
// Structure of a BST node
public class node {
  public int data;
  public node left;
  public node right;
}
 
public class GFG {
 
  // Stores the level of the node and
  // its value at the max level of BT
  static Dictionary<int, List<int> > m
    = new Dictionary<int, List<int> >();
 
  // Stores the maximum level
  static int maxlevel = 0;
 
  // Utility function to create a new BST node
  static node newnode(int d)
  {
    node temp = new node();
    temp.left = null;
    temp.right = null;
    temp.data = d;
    return temp;
  }
 
  // Function to find node of Nth level
  static void findNode(node root, int level)
  {
    // If root exists
    if (root != null)
    {
       
      // Traverse left subtree
      findNode(root.left, level + 1);
 
      // Insert the node's level and
      // its value into the multimap
      if (!m.ContainsKey(level)) {
        m.Add(level, new List<int>());
      }
      m[level].Add(root.data);
 
      // Update the maximum level
      maxlevel = Math.Max(maxlevel, level);
 
      // Traverse the right subtree
      findNode(root.right, level + 1);
    }
  }
 
  // Function to print the L-th node at
  // L-th level of the Binary Tree
  static void printNode(node root, int level)
  {
    // Function Call
    findNode(root, level);
 
    // Iterate all the levels
    for (int i = 0; i <= maxlevel; i++) {
      // Print the current level
      Console.Write("Level " + (i + 1) + ": ");
 
      List<int> it = m[i];
      int flag = 0;
 
      // Iterate upto i-th node of the
      // i-th level
      if (it.Count < i) {
        // If end of the level
        // is reached
        flag = 1;
        Console.WriteLine("-1");
      }
      else {
        // Print the i-th node
        Console.WriteLine(it[i]);
      }
    }
  }
 
  static public void Main()
  {
 
    // Code
    // Construct the Binary 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(12);
    root.left.left.left = newnode(9);
    root.left.left.right = newnode(10);
    root.right.left = newnode(6);
    root.right.right = newnode(7);
    root.right.right.left = newnode(13);
    root.right.right.right = newnode(14);
     
    // Function Call
    printNode(root, 0);
  }
}
 
// This code is contributed by lokeshmvs21.


Javascript




// Stores the level of the node and its value at the max level of BT
const m = new Map();
let maxlevel = 0; // Stores the maximum level
 
// Structure of Binary Tree
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
// Function to insert the node in the Binary Tree
function newnode(d) {
  return new Node(d);
}
 
// Function to find node of Nth level
function findNode(root, level) {
  // If root exists
  if (root) {
    // Traverse left subtree
    findNode(root.left, level + 1);
 
    // Insert the node's level and its value into the map
    if (!m.has(level)) {
      m.set(level, [root.data]);
    } else {
      m.get(level).push(root.data);
    }
    // Update the maximum level
    maxlevel = Math.max(maxlevel, level);
 
    // Traverse the right subtree
    findNode(root.right, level + 1);
  }
}
 
// Function to print the L-th node at L-th level of the Binary Tree
function printNode(root, level) {
  // Function Call
  findNode(root, level);
 
  // Iterate all the levels
  for (let i = 0; i <= maxlevel; i++) {
    // Print the current level
    console.log("Level " + (i + 1) + ": ", m.has(i) ? m.get(i)[i] : -1);
  }
}
 
const 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(12);
root.left.left.left = newnode(9);
root.left.left.right = newnode(10);
root.right.left = newnode(6);
root.right.right = newnode(7);
root.right.right.left = newnode(13);
root.right.right.right = newnode(14);
 
// Function Call
printNode(root, 0);


Output:

Level 1: 1
Level 2: 3
Level 3: 6
Level 4: 12

Time Complexity: O(N), where N is the number of nodes in the Binary Tree.
Auxiliary Space: O(N)

Efficient Approach(using Queue):
Follow the below steps to solve this problem:
1) Perform level order traversal and keep track of level at each node.
2) At each level check if the level number is greater than number of elements in the queue then print 
“-1” else print node which is at level number in current level by comparing level number of nodes pop from queue.

Below is the implementation of above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of Binary Tree
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
// utility function to create a new node
struct Node* newnode(int d){
    Node* temp = new Node();
    temp->data = d;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Function to print the L-th node at
// L-th level of the Binary Tree
void printNode(Node* root){
    int level = 1;
    // initializing queue for level order traversal
    queue<Node*> q;
    q.push(root);
    while(!q.empty()){
        int n = q.size();
        if(level > n) cout<<"Level "<<level<<" : "<<"-1"<<endl;
        for(int i = 0; i<n; i++){
            Node* temp = q.front();
            q.pop();
            if(i == level-1){
                cout<<"Level "<<level<<" : "<<temp->data<<endl;
            }
            if(temp->left) q.push(temp->left);
            if(temp->right) q.push(temp->right);
        }
        level++;
    }
}
 
// Driver code
int main()
{
    // Construct the Binary 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(12);
    root->left->left->left = newnode(9);
    root->left->left->right = newnode(10);
    root->right->left = newnode(6);
    root->right->right = newnode(7);
    root->right->right->left = newnode(13);
    root->right->right->right = newnode(14);
 
    // Function Call
    printNode(root);
    return 0;
}
 
// THIS CODE IS CONTRIBUTED BY KIRIT AGARWAL(KIRITAGARWAL23121999)


Java




// Java program for the above approach structure of binary
// tree
import java.io.*;
import java.util.*;
 
// Structure of Binary Tree
class Node {
  int data;
  Node left;
  Node right;
 
  Node(int data)
  {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
class GFG {
 
  // Function to print the L-th node at L-th level of the
  // Binary Tree
  static void printNode(Node root)
  {
    int level = 1;
    // initializing queue for level order traversal
    Queue<Node> q = new LinkedList<>();
    q.add(root);
    while (!q.isEmpty()) {
      int n = q.size();
      if (level > n)
        System.out.println("Level " + level + " : "
                           + "-1");
      for (int i = 0; i < n; i++) {
        Node temp = q.poll();
        if (i == level - 1) {
          System.out.println("Level " + level
                             + " : " + temp.data);
        }
        if (temp.left != null)
          q.add(temp.left);
        if (temp.right != null)
          q.add(temp.right);
      }
      level++;
    }
  }
 
  public static void main(String[] args)
  {
    // Construct the Binary Tree
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
 
    root.left.left = new Node(4);
    root.left.right = new Node(5);
 
    root.left.right.left = new Node(11);
    root.left.right.right = new Node(12);
    root.left.left.left = new Node(9);
    root.left.left.right = new Node(10);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.right.right.left = new Node(13);
    root.right.right.right = new Node(14);
 
    // Function Call
    printNode(root);
  }
}
 
// This code is contributed by sankar


Python3




# Python program for the above approach
# structure of tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
     
 
# utility function to create a new node
def newnode(d):
    return Node(d)
 
 
# function to print the lth node at
# lth level of the binary tree
def printNode(root):
    level = 1
    q = []
    q.append(root)
    while(len(q) > 0):
        n = len(q)
        if(level > n):
            print("Level", level, " : -1")
        for i in range(n):
            temp = q.pop(0)
            if(i == level-1):
                print("Level", level , " : ", temp.data)
            if(temp.left is not None):
                q.append(temp.left)
            if(temp.right is not None):
                q.append(temp.right)
        level += 1
     
 
# driver code
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(12);
root.left.left.left = newnode(9);
root.left.left.right = newnode(10);
root.right.left = newnode(6);
root.right.right = newnode(7);
root.right.right.left = newnode(13);
root.right.right.right = newnode(14);
 
# function call
printNode(root)


Javascript




// JavaScript program for the above approach
// structure of binary tree
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// utility function to create a new node
function newnode(d){
    return new Node(d);
}
 
// Function to print the L-th node at
// L-th level of the Binary Tree
function printNode(root){
    let level = 1;
    // initializing queue for level order traversal
    let q = [];
    q.push(root);
    while(q.length > 0){
        let n = q.length;
        if(level > n) console.log("Level " + level + " : "<<"-1");
        for(let i = 0; i<n; i++){
            let temp = q.shift();
            if(i == level-1){
                console.log("Level " + level + " : " + temp.data);
            }
            if(temp.left) q.push(temp.left);
            if(temp.right) q.push(temp.right);
        }
        level++;
    }
}
 
// driver program to test above function
let 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(12);
root.left.left.left = newnode(9);
root.left.left.right = newnode(10);
root.right.left = newnode(6);
root.right.right = newnode(7);
root.right.right.left = newnode(13);
root.right.right.right = newnode(14);
 
// function call
printNode(root);


C#




// C# program for the above approach structure of binary
// tree
 
using System;
using System.Collections.Generic;
 
// Structure of Binary Tree
class Node {
    public int data;
    public Node left;
    public Node right;
 
    public Node(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
public class GFG {
 
    // Function to print the L-th node at L-th level of the
    // Binary Tree
    static void printNode(Node root)
    {
        int level = 1;
        // initializing queue for level order traversal
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        while (q.Count > 0) {
            int n = q.Count;
            if (level > n)
                Console.WriteLine("Level " + level + " : "
                                  + "-1");
            for (int i = 0; i < n; i++) {
                Node temp = q.Dequeue();
                if (i == level - 1) {
                    Console.WriteLine("Level " + level
                                      + " : " + temp.data);
                }
                if (temp.left != null)
                    q.Enqueue(temp.left);
                if (temp.right != null)
                    q.Enqueue(temp.right);
            }
            level++;
        }
    }
 
    static public void Main()
    {
 
        // Code
        // Construct the Binary Tree
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
 
        root.left.left = new Node(4);
        root.left.right = new Node(5);
 
        root.left.right.left = new Node(11);
        root.left.right.right = new Node(12);
        root.left.left.left = new Node(9);
        root.left.left.right = new Node(10);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.right.right.left = new Node(13);
        root.right.right.right = new Node(14);
 
        // Function Call
        printNode(root);
    }
}
 
// This code is contributed by karthik


Output

Level 1 : 1
Level 2 : 3
Level 3 : 6
Level 4 : 12

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(b) where b is the maximum width of given binary tree due to queue data structure.



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads