GoAlgo

GoAlgo

BST Search

Search Algorithm

BST Search

Searches for a value in a Binary Search Tree (BST) by repeatedly comparing the target with the current node and moving left or right.

View
No data to display.
Deep Dive

Understanding BST Search in Detail

A Binary Search Tree (BST) is a hierarchical data structure that enables efficient searching, insertion, and deletion. Each node in the tree has at most two children, with the left subtree containing only values less than the node, and the right subtree containing only values greater than the node. This ordering property makes searching extremely efficient.

Imagine an organizational chart where each person knows whether a particular employee works under their left or right subordinate. To find someone, you start at the CEO and ask: "Is this person above or below you in ID number?" Based on the answer, you move to the appropriate branch. You never need to check the entire company—just follow the correct path down the tree.

The Logic Behind Tree Traversal

BST Search leverages the sorted property of the tree to navigate efficiently to the target.

  • Start: Begin at the root node of the tree.
  • Compare: Compare the target value with the current node's value.
  • Found: If they match, the search is complete—return the node.
  • Go Left: If the target is less than the current node, move to the left child.
  • Go Right: If the target is greater than the current node, move to the right child.
  • Not Found: If you reach a null node (no child exists), the target is not in the tree.

Step-by-Step Algorithm Trace

Let's trace the algorithm searching for value 23 in a BST with root 50.

Input Array: BST with nodes: 50, 30, 70, 20, 40, 60, 80, 15, 25, 35, 45
Target: 25

BST Structure:

              50
           /      \
         30        70
        /  \      /  \
      20    40  60    80
     /  \  /  \
   15  25 35  45

Step 1: Start at Root

  • Current node: 50
  • Compare: 25 vs 50
  • 25 < 50 — Go to left child.

Path so far: 50 → ?

Step 2: Traverse Left

  • Current node: 30
  • Compare: 25 vs 30
  • 25 < 30 — Go to left child.

Path so far: 50 → 30 → ?

Step 3: Continue Left

  • Current node: 20
  • Compare: 25 vs 20
  • 25 > 20 — Go to right child.

Path so far: 50 → 30 → 20 → ?

Step 4: Found!

  • Current node: 25
  • Compare: 25 vs 25
  • 25 = 25 — Match found!

Complete path: 50 → 30 → 20 → 25. Found in 4 steps (tree height).

Code Implementation

Below is the implementation of BST Search in multiple programming languages. The algorithm can be implemented both iteratively and recursively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
Node* insert(Node* root, int data) {
if (root == NULL)
return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
Node* search(Node* root, int target) {
// Base case: root is null or target is at root
if (root == NULL || root->data == target)
return root;
// Target is smaller, search left subtree
if (target < root->data)
return search(root->left, target);
// Target is larger, search right subtree
return search(root->right, target);
}
int main() {
Node* root = NULL;
int values[] = {50, 30, 70, 20, 40, 60, 80};
int n = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < n; i++)
root = insert(root, values[i]);
int target = 40;
Node* result = search(root, target);
if (result != NULL)
printf("Element %d found in BST", target);
else
printf("Element %d not found in BST", target);
return 0;
}
C59 lines.c

Time & Space Complexity Analysis

The efficiency of BST Search depends heavily on the shape of the tree. A balanced tree provides optimal performance.

Time Complexity

O(n)Worst Case

This occurs when the tree is completely unbalanced (essentially a linked list). For example, inserting [1, 2, 3, 4, 5] creates a tree where every node only has a right child. Searching for 5 requires checking all n nodes.

O(log n)Average Case

In a reasonably balanced tree, each comparison eliminates roughly half of the remaining nodes, similar to Binary Search on an array.

O(1)Best Case

If the target value is at the root node, only one comparison is needed.

Space Complexity

O(h)Height of Tree

The iterative approach uses O(1) space, while the recursive approach uses O(h) space where h is the height of the tree. In a balanced tree, h = log n; in the worst case, h = n.

When to Use BST Search?

BSTs are ideal when you need a data structure that supports efficient searching, insertion, and deletion—all in one package.

Dynamic Data

Unlike sorted arrays where insertion is O(n), BSTs allow O(log n) insertion while maintaining searchability. This makes them perfect for data that changes frequently.

Range Queries

BSTs excel at finding all values within a range. The tree structure allows you to efficiently skip entire subtrees that fall outside your range.

Ordered Iteration

An in-order traversal of a BST visits all nodes in sorted order. This makes BSTs useful for applications that need both fast search and sorted output.