![]() |
VOOZH | about |
Given a complete binary tree with values indexed from 1 to N and a key K. The task is to check whether a key exists in the tree or not. Print "true" if the key exists, otherwise print "false".
Complete Binary Tree: A Binary Tree is a complete Binary Tree if all the levels are completely filled except possibly the last level and the last level has all keys as left as possible
Examples:
Input: K = 21 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10Output: true
Input: K = 11
1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10
Output: false
Naive Approach: The simplest approach would be to simply traverse the entire tree and check if the key exists in the tree or not.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: The approach is based on the idea that the tree is a complete binary tree and the nodes are indexed from 1 to N starting from the top. So we can track down the path going from the root to the key if at all the key existed. Below are the steps:
Below is the implementation of the above approach:
true
Time Complexity: O(logN)
Auxiliary Space: O(logN)