- 2069 Poush · 3+5 marks
BST properties and recursive search
Short answer
BST properties: left subtree keys < node < right subtree keys; in-order yields sorted order. Recursive search: compare key with root; if equal return node; if less recurse left; else right; null if not found. O(h) time.
What are the properties of a Binary Search Tree (BST)? Explain recursive algorithm to search a BST.
Properties of a Binary Search Tree
- It is a binary tree: every node has at most two children (left and right).
- All keys in the left subtree of a node are smaller than the node's key.
- All keys in the right subtree of a node are greater than the node's key (duplicates are usually not allowed, or are always placed on one side).
- The left and right subtrees are themselves binary search trees.
- In-order traversal visits the keys in ascending order.
- Search, insertion and deletion take O(h) time; h = log n for a balanced tree and n for a skewed one.
Recursive search algorithm
Compare the key with the root. If equal, found; if smaller, search the left subtree; otherwise search the right subtree.
Search(node, key)
1. if node = NULL return NULL (not found)
2. if key = node->info return node (found)
3. if key < node->info return Search(node->left, key)
4. else return Search(node->right, key)
struct node *search(struct node *root, int key) {
if (root == NULL || root->info == key)
return root; /* empty tree or found */
if (key < root->info)
return search(root->left, key); /* go left */
return search(root->right, key); /* go right */
}
Example: BST with root 50 (left 30, right 70; 30 has children 20, 40). Searching 40: 40 < 50 go left; 40 > 30 go right; 40 = 40 found. Three comparisons, one for each node on the path.
Time complexity is O(h): best O(1), average O(log n), worst O(n) for a skewed tree. The recursion depth is also at most h.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Binary tree traversals; preorder of BST · Data Structure and Algorithm, chapter 6
- Binary search with algorithm and example · Data Structure and Algorithm, chapter 8 · asked 4×
- Binary search for 54 in sorted data · Data Structure and Algorithm, chapter 8
- Binary search for 89; hash functions · Data Structure and Algorithm, chapter 8
- Complexity of binary search · Data Structure and Algorithm, chapter 8
- Sequential vs binary search · Data Structure and Algorithm, chapter 8
- Recursive language and its properties · Theory of Computation, chapter 4 · asked 2×
- Decision tree classifier and Hunt's algorithm · Data Mining, chapter 3
- Define tree; properties and applications · Discrete Structure, chapter 4
- Random number properties; KS test algorithm · Simulation and Modeling, chapter 6