Print Leaf Nodes at a given Level in C language

In C programming, printing leaf nodes at a given level in a binary tree involves traversing the tree to a specific level and identifying nodes that have no children. A leaf node is a node whose both left and right pointers are NULL.

Syntax

void printLeafNodes(struct node* root, int level);

Algorithm

The approach uses recursive traversal −

  • Base case: If root is NULL, return
  • Target level: If level == 1, check if current node is a leaf
  • Recursive case: If level > 1, recursively call for left and right subtrees with level-1
11 Level 1 22 33 Level 2 66 44 Level 3 88 77 Level 4 Leaf Nodes at Level 4

Example

Here's a complete program to print leaf nodes at a given level −

#include <stdio.h>
#include <stdlib.h>

// Structure of a binary tree node
struct node {
    int data;
    struct node* left;
    struct node* right;
};

// Function to create a new node
struct node* createNode(int data) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

// Function to print leaf nodes at given level
void printLeafNodes(struct node* root, int level) {
    if (root == NULL)
        return;
    
    if (level == 1) {
        // Check if current node is a leaf node
        if (root->left == NULL && root->right == NULL)
            printf("%d ", root->data);
    } else if (level > 1) {
        // Recursively call for left and right subtrees
        printLeafNodes(root->left, level - 1);
        printLeafNodes(root->right, level - 1);
    }
}

int main() {
    // Creating the binary tree
    struct node* root = createNode(11);
    root->left = createNode(22);
    root->right = createNode(33);
    root->left->left = createNode(66);
    root->right->right = createNode(44);
    root->left->left->left = createNode(88);
    root->left->left->right = createNode(77);
    
    int level = 4;
    printf("Leaf nodes at level %d are: ", level);
    printLeafNodes(root, level);
    printf("<br>");
    
    return 0;
}
Leaf nodes at level 4 are: 88 77

How It Works

The algorithm works by recursively traversing the binary tree:

  1. Level 1: Check if current node is a leaf (both children are NULL)
  2. Level > 1: Recursively visit left and right children with decremented level
  3. Base case: If node is NULL, simply return

Time and Space Complexity

Complexity Value Description
Time O(n) Visits each node once in worst case
Space O(h) Recursive stack space, where h is tree height

Conclusion

Printing leaf nodes at a specific level requires recursive traversal with level tracking. The algorithm efficiently identifies leaf nodes by checking if both left and right pointers are NULL at the target level.

Updated on: 2026-03-15T11:56:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements