Binary Search Tree (BST)
A Binary Search Tree is a node-based data structure that maintains sorted data and allows for efficient search, insertion, and deletion operations. Each node has at most two children, with values in the left subtree being less than the parent and values in the right subtree being greater or equal.Try the interactive visualizer: Binary Tree Visualizer
Structure
Each node in a BST contains:- value: The data stored in the node
- leftChild: Pointer to the left child node (smaller values)
- rightChild: Pointer to the right child node (greater or equal values)
Key Operations
- Insert
- Search
- Height
Insert Operation
Insertion in a BST follows the binary search property to find the correct position for the new value.Algorithm:- If the tree is empty, create the root node
- Start from the root and compare the value
- If value < current node, traverse left
- If value >= current node, traverse right
- Insert when an empty position is found
Properties
BST Invariant
BST Invariant
The fundamental property of BSTs:
- All values in the left subtree < parent value
- All values in the right subtree >= parent value
- This property holds recursively for all subtrees
Performance Characteristics
Performance Characteristics
Balanced BST:
- Search: O(log n)
- Insert: O(log n)
- Delete: O(log n)
- Space: O(n)
- All operations degrade to O(n) when the tree becomes a linked list
Use Cases
Use Cases
- Maintaining sorted data with dynamic insertions/deletions
- Database indexing
- File system organization
- Expression parsing
- Priority queues (when balanced)
Interactive Visualizer
The Binary Tree visualizer provides:- Insert: Add values and watch the tree grow dynamically
- Visual feedback: See how values are placed according to BST rules
- Animated operations: Understand the insertion algorithm step-by-step
Try it Live
Experiment with the interactive Binary Search Tree visualizer to see insertions in real-time
Code Implementation
The visualizer implements the BST using TypeScript with the following key features:Related Topics
Tree Traversals
Learn about different ways to traverse binary trees
General Tree
Explore general tree structures with multiple children