Output: Found Not Found Found Found Found Found Not Found
Naive Approach:
For each element, we will try to search for that element in the BST.
Time Complexity: O(N * M) as the tree is not balanced the height may become M. In that case, the overall complexity of searching will become O(N * M) Auxiliary Space: O(1)
Efficient Approach: The operations can be performed efficiently by following the below idea:
First store the In-Order Traversals in an array and using binary search for searching the elements in that array because the inorder traversal of the BST will always give a sorted array.
Follow the below steps to solve the problem:
Do a inorder traversal of the BST. i.e. O(M) time.
Store the in-order traversal in the array.
The array is sorted. As the inorder traversal of BST is in a sorted fashion.
As it is Left Root Right. All Left elements are smaller than the root, all right elements are larger than root.
Now simply use the binary search in the array.
Return the answer.
Below is the Implementation of the above approach.
Output
Found
Not Found
Found
Found
Found
Found
Not Found
Time Complexity : O(M + N * log M)
In-order traversal takes O(M) for once
BST Search is now optimized to O(log M) always irrespective of the height of BST.
Auxiliary Space: O(M), The In-order traversal needs to be stored in arrays.