Print all Nodes of Binary Tree at Given Level

  • Write a C program to print all nodes of binary tree at given level.

Given a binary tree and a level L, we have to print all the nodes of binary tree at level L.


Algorithm to print nodes at given level
Let "node" be the pointer to any node of binary tree and we want to print all nodes at level L.
We will do pre order traversal of given binary tree and keep track of the level of current node. If level of current node is equal to L then we will print it on screen else continue pre order traversal.
  • If node is equal to NULL, return.
  • If level of node is equal to L, then print node and return.
  • Recursively traverse left and right sub trees at level L + 1.
Time Complexity : O(n), n is the number of nodes in binary tree. We are traversing binary tree only once.

C program to print all nodes of binary tree at a given level

#include <stdio.h>

struct node {
    int data;
    struct node *left;
    struct node *right;
};

struct node* getNewNode(int data) {
  /* dynamically allocate memory for a new node */ 
  struct node* newNode = (struct node*)malloc(sizeof(struct node));
 
  /* populate data in new Node */
  newNode->data = data;
  newNode->left = NULL;
  newNode->right = NULL;
  
  return newNode;
}

/*
This function returns below tree
            1
           / \
         2    3
        / \    \
       4  5    7
      / \
     8  9
*/
struct node* generateBTree(){
    // Root Node
    struct node* root =  getNewNode(1);

    root->left = getNewNode(2);
    root->right = getNewNode(3);

    root->left->left = getNewNode(4);
    root->left->right = getNewNode(5);
    root->right->right = getNewNode(7);
 
    root->left->left->left = getNewNode(8);
    root->left->left->right = getNewNode(9);
    
    return root;
}

/* 
   Prints all node at a particular level. It does pre Order 
   traversal and keeps track of the current level.
   If current level is equal to the level, it prints current node
*/
void printNodesAtLevel(struct node* root, int currentLevel, int level) {
  
  if(root == NULL) {
      return;   
  }  
  if(currentLevel == level) {
     printf(" %d ", root->data);
     return;
  }
             
  printNodesAtLevel(root->left, currentLevel+1, level);
  printNodesAtLevel(root->right, currentLevel+1, level);
}

int main() {
    struct node *root = generateBTree();    
    
    /*Printing all nodes at level 2*/
    printNodesAtLevel(root, 0, 2);
    
    getchar();
    return 0; 
}
Output
 4  5  7