Searching in a Binary Search Tree (BST) is an efficient process due to the properties of the BST. A BST is a binary tree where:
- The value of each node in the left subtree is less than the value of the root.
- The value of each node in the right subtree is greater than the value of the root.
- These properties apply recursively to all subtrees.
Algorithm for Searching in a BST
To search for a key in a BST, the following steps are used:
- Start at the root of the tree.
- Compare the key to be searched with the value of the current node:
- If the key matches the current node value, the search is successful.
- If the key is less than the current node value, move to the left subtree.
- If the key is greater than the current node value, move to the right subtree.
- Repeat the process until:
- The key is found, or
- A
NULL
(empty subtree) is encountered, meaning the key is not in the tree.
Recursive Implementation
Iterative Implementation
Time Complexity
- Best Case: O(1)O(1) — The key is found at the root.
- Average Case: O(logn)O(\log n) — The height of the BST (assuming it is balanced).
- Worst Case: O(n)O(n) — The tree is skewed (all nodes in one branch).
Space Complexity
- Recursive: O(h)O(h) — Due to the recursive call stack, where hh is the height of the tree.
- Iterative: O(1)O(1) — No additional space is used beyond the variables.
Advantages of BST Search
- Efficient for searching, especially in balanced BSTs.
- Provides a logical framework for searching based on comparison.
Applications
- Database indexing.
- Auto-complete suggestions.
- Implementing sets and maps in programming languages.
By leveraging the properties of a BST, the search process becomes both intuitive and efficient.