Home
DSA Visualizer
Data Structures
Binary Search Tree
Binary Search Tree
A binary search tree is a hierarchical data structure in which each node has at most two children, with left child < parent < right child.
READY
In-order output
Insert a value, or press Random for a tree to search. Every operation walks down from the root.
Value
Order
Intuition
Imagine a family tree where every parent has at most two children. In a BST, we organize numbers so that everything to the left is smaller and everything to the right is larger. This makes finding a number very fast—like looking up a word in a dictionary!
Concept
In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. That one ordering rule lets a search skip an entire subtree at every step: O(log n) when the tree is balanced, but O(n) when values arrive already sorted and the tree degenerates into a line.
How it Works
- Root: The top node of the tree.
- Left Subtree: Contains values smaller than the root.
- Right Subtree: Contains values larger than the root.
- Leaf: A node with no children.
Step-by-Step Breakdown
- Start at the Root.
- If
Value < CurrentNode.Value, go Left. - If
Value > CurrentNode.Value, go Right. - If you reach an empty spot (NULL), insert the new node there.
When to Use
- Fast Lookup: Searching is O(log n) on average.
- Sorted Data: In-order traversal gives sorted elements.
- Dynamic Data: Efficient insertions and deletions compared to arrays.
When NOT to Use
- Unbalanced Trees: In worst case (skewed tree), operations become O(n).
- Constant Time Access: If you need O(1) access by index (use Array).
How to Identify
Look for problems involving searching, sorting, or maintaining a dynamic sorted set of elements. Keywords: "Binary Search", "Tree", "Hierarchy", "Sorted".
Applying for software engineering roles? Free, no sign-up:
