VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-levels-nodes-binary-tree/

⇱ Print Levels of all nodes in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Levels of all nodes in a Binary Tree

Last Updated : 3 Mar, 2023

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, then your function should return 0.

👁 Image

Input:
 3
 / \
 2 5
 / \
 1 4

output:
 Level of 1 is 3
 Level of 2 is 2
 Level of 3 is 1
 Level of 4 is 3
 Level of 5 is 2

We have discussed an recursive solution in below post. 
Get Level of a node in a Binary Tree

In this post, an iterative solution based on Level order traversal is discussed. We store level of every node in queue together with the node while doing the traversal. 

Algorithm:

Step 1: Start 
Step 2: Create a class of static type name it as pair which have two parameter one of node type an danother is of integer type.
Step 3: create a function of static type with null return type nameas "printLevel" which take raaotof linked list as input.
            a. Set base condition as if ( root == null ) return
            b. Create a queue to hold the tree nodes and their levels name it as "q".
            c. add root node at level 1 in q
            d. Define a pair variable p.
            e. start a while loop to do level-order traversal until queue is empty:
               1. Dequeue a node and its level into the pair variable p at the front of the queue.
               2. Print the data and the node's level
               3. Enqueue the node's left child with its level increased by 1 if it has one.
               4. Enqueue the node's right child with its level increased by 1 if it has one.

step 4: End

Implementation:


Output
Level of 3 is 1
Level of 2 is 2
Level of 5 is 2
Level of 1 is 3
Level of 4 is 3

Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
Auxiliary Space: O(n) where n is the number of nodes in the given Binary tree due to queue data structure.
 

Comment
Article Tags: