Course contentsShow
← C
Lesson 1027 of 1,21914. Data Structures in CFree lesson

Searching for a value in BST

Searching for a value in BST

What you'll learn: How to efficiently locate a specific piece of data within a Binary Search Tree by leveraging its sorted structure.

The "High-Low" Strategy

Searching a Binary Search Tree (BST) is remarkably like playing a game of "Guess the Number." If I’m thinking of a number between 1 and 100 and you guess 50, I’ll tell you if my number is higher or lower. You immediately discard half of the possibilities.

In a BST, every node acts as that "50." Because of the BST property—where smaller values live to the left and larger values live to the right—you never have to search the entire tree. You simply compare your target value to the current node and decide which branch to take.

How the Search Works

Imagine you are looking for the number 7 in a tree:

  1. Start at the Root: Is the root 7? If yes, you're done!
  2. Go Left if Smaller: If 7 is less than the current node, move to the left child.
  3. Go Right if Larger: If 7 is greater than the current node, move to the right child.
  4. Repeat: Keep doing this until you find the node or hit a NULL pointer (which means the value isn't in the tree).

Searching in Code

We can implement this using a simple recursive function. If the current root is null, the value doesn't exist. If the data matches, we return the node. Otherwise, we "recurse" down the correct path.

struct Node {
    int data;
    struct Node *left, *right;
};

// Returns the node containing the target, or NULL if not found
struct Node* search(struct Node* root, int target) {
    // Base Case: Tree is empty or we found the target
    if (root == NULL || root->data == target) {
        return root;
    }

    // Target is greater than root's data, search in right subtree
    if (target > root->data) {
        return search(root->right, target);
    }

    // Target is smaller, search in left subtree
    return search(root->left, target);
}

Why It’s Fast

In a balanced tree, each step you take cuts the remaining search area in half. Instead of checking every single element (like you would in an array or linked list), you can find one value out of a million in roughly 20 steps. This is known as O(log n) time complexity.

Key takeaway

To search a BST, compare the target to the current node and move either left or right, effectively halving the remaining search space at every step.