Properties of a Binary Search Tree
What you'll learn: How the specific arrangement of nodes in a Binary Search Tree enables lightning-fast data retrieval.
The Rule of Order
A Binary Search Tree (BST) isn't just a collection of nodes; it is a highly organized filing system. While a standard binary tree allows any node to have two children, a BST adds a strict rule to how those children are placed.
Imagine you are standing at a specific node (let’s call its value the "Root"). In a BST, every single value in the left subtree must be smaller than the Root, and every single value in the right subtree must be larger than the Root. This rule applies recursively to every single node throughout the entire tree.
The Library Analogy
Think of a BST like a librarian organizing a section of books. If you are looking for a book titled "Moby Dick," and you start at a shelf labeled "Great Gatsby," you don't need to look at every single shelf. Because the library is sorted, you know "Moby" comes after "Great," so you move strictly to the right. By following this logic, you ignore half of the library with every step you take. This makes searching incredibly efficient.
A BST in Code
To maintain these properties, our C structure remains a standard node, but our logic for inserting and finding data must respect the "Left < Root < Right" rule.
#include <stdio.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Logical property check:
// For any node 'N':
// All nodes in N->left have data < N->data
// All nodes in N->right have data > N->data
/*
50 (Root)
/ \
30 70
/ \ / \
20 40 60 80
*/
Why This Matters
Because of this property, a BST never requires you to look at every node to find a value. If you are looking for 60 in the example above, you start at 50. Since 60 > 50, you go right. Then you see 70. Since 60 < 70, you go left. You’ve found your target in just two steps, even though the tree has seven nodes. This efficiency is why BSTs are the foundation for many complex databases and search algorithms.
Key takeaway
In a BST, every left child is smaller than its parent, and every right child is larger, allowing you to find data by discarding half the remaining tree at each step.