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.
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.
# Python3 program to pr levels
# of all nodes
# Helper function that allocates a new
# node with the given data and None
# left and right poers.
# Construct to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def prLevel( root):
if (not root):
# queue to hold tree node with level
q = 
# let root node be at level 1
p = 
# Do level Order Traversal of tree
p = q
print(“Level of”, p.data, “is”, p)
q.append([p.left, p + 1])
q.append([p.right, p + 1 ])
# Driver Code
if __name__ == ‘__main__’:
Let us create Binary Tree shown
in above example “””
root = newNode(3)
root.left = newNode(2)
root.right = newNode(5)
root.left.left = newNode(1)
root.left.right = newNode(4)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
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.
This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print all nodes between two given levels in Binary Tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print the nodes at odd levels of a tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print all even nodes of Binary Search Tree
- Print all full nodes in a Binary Tree
- Print all internal nodes of a Binary tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Print all nodes in a binary tree having K leaves