What is a tree?#
A tree stores data in a hierarchy - like a family tree, a company org chart, the folders on your computer or the HTML DOM.
50 <- root (level 0)
/ \
30 70 <- children of 50
/ \ / \
20 40 60 80 <- 20, 60, 80 are leaves (no children)
/
35
| Term | Meaning |
|---|---|
| root | the top node (no parent) |
| parent / child | a node and the nodes directly below it |
| leaf | a node with no children |
| subtree | a node and everything below it |
| depth of a node | number of edges from the root |
| height of a tree | number of levels (nodes on the longest root-to-leaf path) |
A binary tree gives every node at most two children: left and right.
Tree एक उल्टे पेड़ जैसा है - सबसे ऊपर root (जड़), नीचे शाखाएं, और सबसे नीचे leaf (पत्तियाँ) जिनके आगे कोई child नहीं। आपके computer के folders भी ऐसे ही हैं: एक drive के अंदर folders, उनके अंदर और folders, और आखिर में files (leaves)।
Binary Search Tree (BST)#
A BST keeps this rule at every node: values in the left subtree are smaller, values in the right subtree are larger. Searching then works like binary search - go left or right, never both.
Inorder: 20 30 35 40 50 60 70 80 Preorder: 50 30 20 40 35 70 60 80 Postorder: 20 35 40 30 60 80 70 50 Search 60: found Search 65: not found
Traversals#
| Traversal | Order | Used for |
|---|---|---|
| Inorder | left, node, right | sorted output of a BST |
| Preorder | node, left, right | copying / saving a tree |
| Postorder | left, right, node | deleting a tree, evaluating expression trees |
| Level order | level by level, using a queue | shortest path in a tree, printing by levels |
Level 0: 50 Level 1: 30 70 Level 2: 20 40 60 80
Complexity and balance#
| Operation | Balanced BST | Skewed BST (worst case) |
|---|---|---|
| search | O(log n) | O(n) |
| insert | O(log n) | O(n) |
| delete | O(log n) | O(n) |
If you insert sorted data (10, 20, 30, 40...) every node goes right and the "tree" becomes a linked list. Self-balancing trees - AVL trees and red-black trees - rotate nodes to keep the height about log n.
You rarely write a balanced tree yourself. C++ std::set and std::map are red-black trees: insert, find and erase are O(log n), and iterating gives sorted order.
#include <set>
#include <map>
set<int> s = {50, 20, 70};
s.insert(30);
bool has = s.count(30); // true
map<string, int> marks; // key -> value, kept sorted by key
marks["Asha"] = 92;
marks["Ravi"] = 78;
for (auto& [name, m] : marks) cout << name << " " << m << "\n";
Summary#
- Trees store hierarchy; binary trees have left and right children.
- BST rule: left < node < right → search/insert in O(height).
- Inorder (sorted), preorder, postorder (recursive) and level order (queue).
- Keep trees balanced for O(log n); in C++ use
set/map.