![]() |
VOOZH | about |
Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree.
Examples:
Input : key = 4
👁 ex-3👁 ex-3
Output: 3
Explanation: The level of the key in above binary tree is 3.
Input : key = 10Output: -1
Explanation: Key is not present in the above Binary tree.
Table of Content
The idea is to start from the root and level as 1. If the target matches with root's data, return level. Else recursively call for left and right subtrees with level as level + 1.
Below is the implementation of the above approach:
3
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(h), where h is height of binary tree.
The idea is to perform a level-order traversal and keep track of the current level as we traverse the tree. If the key matches with root's data, return level.
3
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(n)