Given a level-order sorted complete binary tree, the task is to check whether a key exists in it or not. A complete binary tree has every level except possibly the last, completely filled, with all nodes as far left as possible.
Examples:
7
/ \
10 15
/ \ / \
17 20 30 35
/ \ /
40 41 50
Input: Node = 3
Output: No
Input: Node = 7
Output: Yes
Input: Node = 30
Output: Yes
Approach A simple O(n) solution would be to fully traverse the tree and check for the key value. However, we can leverage the information that the tree is sorted and do better in terms of time complexity.
- Find out the level where the key may exist. Start at the root node, keep going left until a value which is greater than the key value is encountered. The level before this would contain the key, if at all the key existed in the tree. Let us assume this is level l.
- Now, perform binary search on the nodes of l. Unlike the conventional binary search, the nodes of this level cannot be accessed directly. However, the path from the root to every node in this level can be encoded using the binary logic. For example, consider the 3rd level in the sample tree. It can contain up to 23 = 8 nodes. These nodes can be reached from the root node by going left, left, left; or by going left, left, right; and so on. If the left is denoted by 0 and the right by 1 then the possible ways to reach nodes in this level can be encoded as arr = [000, 001, 010, 011, 100, 101, 110, 111].
- However, this array doesn't need to be created, binary search can be applied by recursively selecting the middle index and simply generating the l-bit gray code of this index (Refer to this article).
- In case of incomplete paths, simply check for the left part of the array. For instance, the encoded path 011 does not correspond to any value in the sample tree. Since the tree is complete, it ensures that there will be no more elements to the right.
- If the key is found return true, else return false.
Below is the implementation of the above approach:
Time Complexity: The level can be found in O(logn) time. The time to traverse any path to perform binary search is O(logn). Further, in the worst case, the level may have at most n/2 nodes.
Therefore, the time complexity of performing search becomes O(logn)*O(log(n/2)) = O(logn)^2.
Auxiliary Space: O(1).