⚡0 XP🔥0

Trees and Binary Search Trees

Lesson 6 of 7 ⏱ 5 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs C++

Tree vocabulary (root, child, leaf, height), binary trees, preorder, inorder, postorder and level-order traversals, binary search trees with insert and search, and balanced trees in the STL (set and map).

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.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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
▶ Try it YourselfC++
Ctrl + Enter to run
Output
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.

Tip

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.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Height of a tree

Complete the recursive function height - the number of nodes on the longest path from the root down to a leaf (an empty tree has height 0). For the tree built in main the longest path is 50 → 30 → 40 → 35 → 37, so the program prints Height: 5.

Expected output:
Height: 5
2

Sum of leaf nodes

Write leafSum that returns the sum of all leaf nodes (nodes with no children). For the same tree the leaves are 20, 37, 60 and 80, so it prints Leaf sum: 197.

Expected output:
Leaf sum: 197

Quick Quiz

Q1.

In a binary tree, each node has at most how many children?

Q2.

Which traversal of a binary search tree prints the values in sorted order?

Q3.

In a BST, where is a value smaller than the current node stored?

Q4.

What is the time to search a balanced BST with n nodes?

Q5.

Inserting 1, 2, 3, 4, 5 in this order into a plain BST produces...