Imagine a family tree.
- It starts with one person (like a grandparent) at the top.
- That person has children.
- Those children may have their own children.
- And so on…
A tree in programming works in a similar way.
- It starts with one main item (called the root).
- That item can have other connected items (children).
- These items may have their own children too.
This structure is useful for organizing things that have a “hierarchy” — like folders in your computer or choices in a game.
Binary Tree
Imagine a simple “yes or no” game.
Each question leads to two possible answers — yes or no — which makes this a binary tree.
Use Cases:
- Games with choices
- Decision-making systems
- Data storage with 2-way options
Binary Search Tree (BST)
A special binary tree where: All left children are smaller, All right children are larger.
Let’s say we want to store numbers: 10, 5, 15
The BST will look like this:
- 5 is smaller than 10 → goes to the left
- 15 is bigger than 10 → goes to the right
Why is this useful?
You can find a number faster, just like how you find a word in a dictionary by not starting from page 1.
Use Cases:
- Fast searching
- Fast sorting
- Making data easy to find
AVL Tree (Self-Balancing Tree)
A type of Binary Search Tree that keeps itself balanced.
Why is this needed? Sometimes in a BST, everything goes to one side and becomes like a long stick — slow to search.
AVL Tree keeps the tree balanced
Every time you add or remove data, it makes sure the tree stays “even” on both sides.
Example:
If you add these numbers in this order: 30, 20, 10
A simple BST would look like:
But an AVL Tree will rearrange (rotate) it to:
Now it’s faster to find anything!
Use Cases:
- Databases
- Real-time systems where speed matters.
Segment Tree
A tree used to do fast calculations on ranges of data.
Imagine you have this list of numbers:
Now, someone asks: “What’s the sum from position 2 to 4?”
You could add 4 + 6 + 8 = 18, right?
But what if someone asks this kind of question 1000 times?
A Segment Tree stores pre-calculated results in parts (segments), so you can get the answer super fast without calculating every time.
Example:
- You can ask: "What’s the sum from 1 to 3?"
- Or: "What’s the biggest number from 2 to 5?"
Use Cases:
- Stock price tracking
- Range search in games
- Apps with live stats
Trie (Prefix Tree)
A tree used to store and search words fast, especially by their prefix (starting letters)
Example:
Imagine storing words: cat, cap, car
A Trie stores them like this:
Now if someone types "ca", the Trie already knows all words starting with ca: cat, cap, car
Use Cases:
- Autocomplete in Google
- Spell-checking
- Word games like Scrabble or Boggle
Published :