Module 5 · 18 min read · Free chapter
Trees, binary search trees and binary heaps
A binary tree of height h has at most 2ʰ⁺¹ − 1 nodes, and every binary tree has one more leaf than two-child nodes. A BST keeps smaller keys left and larger keys right, so inorder is sorted and operations cost Θ(h). A binary heap lives in an array, build-heap is Θ(n) and insert or delete-min is Θ(log n).
Start from zero: a family tree
Many families keep a vanshavali, a record of who descends from whom. At the top sits the eldest ancestor, below him his children, below them the grandchildren, and so on. Each person has exactly one parent line above them, but a person may have several children below.
Computer scientists draw the same picture and call it a tree, only they draw it upside down, with the root at the top. Each person is a node, the lines are edges, and people with no children are leaves. Your school's office chart, from principal to teachers to class monitors, is a tree too.
Trees appear wherever data has a natural "inside of" or "under" relation. Folders inside folders on your computer form a tree, and so does the structure of a web page. A compiler also turns every arithmetic expression into a tree before it works it out.
This chapter builds three tools on this one shape. The binary tree limits each node to two children, the binary search tree keeps keys in order for fast search, and the binary heap keeps the smallest key on top for fast priority work.
Why it matters. Lists and arrays force every search to go one step at a time, but a well-shaped tree halves the work at every level. That is how a database finds one record among crores in a handful of steps.
Tree vocabulary and binary tree counts
A few words do most of the work. The parent of a node is the node just above it, its children are the nodes just below, and nodes with the same parent are siblings. The depth of a node is the number of edges from the root to it, and the height of the tree is the largest depth of any node.
In this chapter a single node has height , and an empty tree has height . Some papers count levels from instead, so always read the convention in the question. A tree with nodes always has exactly edges, because every node except the root has one edge to its parent.
A binary tree allows each node at most two children, called left and right. Three counting facts follow from this limit:
- Level , with the root at level , holds at most nodes, because each level can at most double the one above.
- A tree of height holds at most nodes, which is reached by a perfect binary tree.
- So nodes need height at least , while the largest possible height is , a chain.
Leaves and two-child nodes. Let , and be the numbers of nodes with , and children. Counting edges two ways gives , and since , we get
Worked example. A binary tree has nodes with two children and nodes with one child. Then it has leaves and nodes in all. Every node has two child pointers, so there are pointers, of which are used by edges and are NULL.
A full binary tree, in which every node has or children, is a special case with . With internal nodes it has leaves and nodes in all. A complete binary tree fills every level fully except possibly the last, which is filled from the left, and this is the shape a heap uses.
Why it matters. GATE asks these counts directly, often as "how many leaves" or "what is the smallest height". The same counts also explain why balanced trees give search times.
Traversals and rebuilding a tree
A traversal visits every node once in a fixed order. Three orders are defined recursively by when the root is visited, and a fourth goes level by level. Take the tree with root A, whose left child B has children D and E, and whose right child C has a left child F.
| Traversal | Rule | Order for the example |
|---|---|---|
| Preorder | root, left, right | A B D E C F |
| Inorder | left, root, right | D B E A F C |
| Postorder | left, right, root | D E B F C A |
| Level order | level by level, left to right, using a queue | A B C D E F |
Each traversal touches every node a constant number of times, so all four take time. The recursive ones use stack space equal to the height, while level order keeps a queue that can hold a whole level. Inorder is the one to remember for search trees, because it lists their keys in sorted order.
Rebuilding a tree from two traversals. Suppose you are given preorder A B D E C F and inorder D B E A F C. The first preorder symbol, A, is the root. In the inorder list, everything left of A (D B E) is the left subtree and everything right of it (F C) is the right subtree.
Now repeat on each part. In preorder the left part appears as B D E, so B is its root, with D on its left and E on its right. The right part appears as C F, so C is its root, and since F lies left of C in the inorder list, F is C's left child.
This works because inorder separates left from right once the root is known. So inorder together with any one of preorder, postorder or level order fixes the tree, if the keys are distinct. Preorder and postorder alone cannot always do it: the trees "A with left child B" and "A with right child B" both give preorder A B and postorder B A.
Why it matters. "Find the postorder, given the preorder and inorder" is among the most frequent GATE questions on trees. The same splitting idea also teaches the divide-and-conquer style of thinking used all through algorithms.
Counting distinct binary trees and BSTs
How many differently shaped binary trees can be made with nodes? Pick which node is the root's left subtree size, say , and the right subtree then has nodes. Adding over all choices of gives the Catalan recurrence:
Its closed form is . For example, and .
| Nodes n | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Shapes, and BSTs on n keys | 1 | 1 | 2 | 5 | 14 | 42 | 132 |
The same count for BSTs. Given distinct keys, every tree shape can be filled with them in exactly one way that obeys the search-tree rule, by placing the keys in inorder. So the number of different BSTs on keys is also , and keys 1, 2 and 3 give BSTs.
If the root must be key , then keys to form the left subtree and keys to form the right one. So the number of BSTs with root is . With and root this is .
Labelled trees. If the nodes carry distinct labels with no ordering rule, each shape can be labelled in ways. So there are labelled binary trees, which is for .
Why it matters. GATE has asked the number of distinct BSTs several times, sometimes with a fixed root or a fixed height. Knowing the values up to by heart saves the calculation in the exam hall.
Binary search trees: search, insert, delete
A binary search tree (BST) is a binary tree with one rule at every node: all keys in the left subtree are smaller than the node's key, and all keys in the right subtree are larger. To search, compare with the root and go left or right, throwing away one subtree at each step.
struct tnode { int key; struct tnode *left, *right; };
struct tnode *search(struct tnode *t, int k) {
while (t != NULL && t->key != k)
t = (k < t->key) ? t->left : t->right;
return t; /* NULL if k is absent */
}
Insertion follows the same path until it falls off the tree, and the new key becomes a leaf at that spot. Insert 50, 30, 70, 20, 40, 60 and 80 in that order, and you get 50 at the root, 30 and 70 below it, and the other four keys as leaves. Its inorder traversal is 20 30 40 50 60 70 80, which is sorted, as it always is for a BST.
Deletion has three cases:
- A leaf, such as 20, is simply removed.
- A node with one child is replaced by that child; after 20 is gone, deleting 30 lifts 40 into its place.
- A node with two children, such as the root 50, takes the key of its inorder successor, the smallest key in its right subtree, which is 60; then the old node 60, a leaf, is deleted.
The inorder predecessor, the largest key in the left subtree, works equally well in case 3. Either choice keeps the search-tree rule, because the successor is larger than everything on the left and smaller than everything else on the right.
Cost. Every operation walks one path from the root, so it takes time for height . A random BST has height about , but inserting keys in sorted order, such as 10, 20, 30, 40, builds a chain of height , and then search is as slow as a linked list.
Why it matters. The BST is the idea behind ordered maps and sets in every programming language. Its weak point, the chain, is exactly why balanced trees such as AVL trees were invented.
AVL trees and rotations, briefly
An AVL tree is a BST that repairs itself. At every node the heights of the left and right subtrees may differ by at most ; this difference is the balance factor, which must be , or . That one rule keeps the height at , so search, insert and delete all stay in the worst case.
After an insertion, walk back up towards the root and find the first node whose balance factor has become or . The new key went into one of four places below it, and each place has its own fix:
- LL case (into the left child's left subtree): one right rotation at the unbalanced node.
- RR case (into the right child's right subtree): one left rotation.
- LR case (into the left child's right subtree): a left rotation at the child, then a right rotation at the node.
- RL case (into the right child's left subtree): a right rotation at the child, then a left rotation at the node.
Worked example. Insert 10, 20 and 30 into an empty AVL tree. After 30 arrives, node 10 has a right subtree of height and an empty left subtree of height , so its balance is , an RR case. One left rotation at 10 makes 20 the root with 10 and 30 as its children.
Now insert 30, 10 and then 20 instead. Node 30 becomes unbalanced through its left child's right side, an LR case. A left rotation at 10 followed by a right rotation at 30 again gives 20 at the root.
How thin can an AVL tree be? Let be the fewest nodes in an AVL tree of height . The thinnest tree has one subtree of height and the other of height , so
This gives , , and . These numbers grow like Fibonacci numbers, which is exactly why the height is logarithmic in .
Why it matters. Rotations are the basic move of every self-balancing tree. GATE asks for the tree after a few insertions, or for the largest height possible with a given number of nodes, which you read off the list.
Binary heaps, heapify and build-heap
A binary heap is a complete binary tree with the heap property: in a min-heap every parent is at most its children, so the smallest key sits at the root. A max-heap reverses the rule. Unlike a BST, a heap says nothing about left versus right, so it cannot search for an arbitrary key quickly.
Because the tree is complete, it fits in an array with no gaps and no pointers. With indices from , node has children and and parent ; with indices from , as in C, the children are and . A heap of keys has height , and its leaves occupy indices to .
Heapify (sift down). If both subtrees of node are heaps but node itself may be too large, swap it with its smaller child and repeat lower down. This walks at most one path to a leaf, so it costs .
Build-heap. To turn an arbitrary array into a heap, call heapify on indices down to , since the leaves are already heaps. Take the array 9, 5, 8, 2, 4, 7, 1 with :
- At index 3 the key 8 swaps with its smaller child 1, giving 9, 5, 1, 2, 4, 7, 8.
- At index 2 the key 5 swaps with 2, giving 9, 2, 1, 5, 4, 7, 8.
- At index 1 the key 9 swaps with 1 and then with 7, giving the min-heap 1, 2, 7, 5, 4, 9, 8 after only 4 swaps.
It looks like calls of each, but most nodes are near the bottom and sink very little. About nodes have height , so the total work is
So bottom-up build-heap runs in , which beats inserting the keys one by one in .
Insert and delete-min. To insert, place the new key at index and sift it up while it is smaller than its parent. Inserting 3 into the heap above puts it at index 8 under 5, one swap lifts it to index 4, and it stops under 2. To delete the minimum, move the last key to the root and sift it down; removing 1 from 1, 2, 7, 5, 4, 9, 8 gives 2, 4, 7, 5, 8, 9. Both operations cost , and reading the minimum costs .
Repeating delete-min times outputs the keys in sorted order, and this is heap sort: time, in place, but not stable. It is compared with the other sorting methods in searching and sorting.
Why it matters. Heaps are the standard way to build priority queues, used in CPU scheduling, shortest-path algorithms and the merging of sorted files. GATE asks for the array after a build-heap or a few deletions almost every year, so practise the index arithmetic until it is automatic.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about trees in four ways:
- They ask you to define tree terms and prove a counting fact, such as .
- They ask you to construct a tree from two traversals or from a sequence of BST insertions, and to traverse it.
- They ask you to explain BST deletion with all three cases, or AVL rotations with a figure for each case.
- They ask you to build a heap from an array, show each step, and justify why build-heap is linear.
Practice questions (our own, not previous-year questions).
- Prove that in any binary tree the number of leaves is one more than the number of nodes with two children. (10 marks)
- Insert 45, 25, 65, 15, 35, 55 and 75 into an empty BST, then delete 45 and draw the tree after each step. (10 marks)
- Build a min-heap from the array 9, 5, 8, 2, 4, 7, 1, showing every swap, and prove that bottom-up build-heap runs in linear time. (15 marks)
Answer plan for question 3.
- Begin by defining a min-heap as a complete binary tree in which each parent is at most its children.
- Draw the array as a complete tree and note that indices 4 to 7 are leaves, so heapify starts at index 3.
- Show the three heapify calls at indices 3, 2 and 1 with the array after each, ending at 1, 2, 7, 5, 4, 9, 8.
- Explain that a node at height can sink at most levels, and that about nodes have height .
- Add these costs as and state that the series is at most times a constant, so the total is .
- Conclude that inserting the keys one by one costs , so the bottom-up method is better, and mention its use in heap sort.
Quick revision
- A tree with nodes has edges, and here a single node has height .
- A binary tree of height has at most nodes, and every binary tree has .
- Preorder is root-left-right, inorder is left-root-right, postorder is left-right-root, and level order uses a queue.
- Inorder with any one other traversal fixes a tree, but preorder with postorder does not in general.
- There are shapes and BSTs on keys: 1, 1, 2, 5, 14, 42, 132.
- BST operations cost , which is for a chain built from sorted input.
- A node with two children is deleted by copying in its inorder successor or predecessor.
- AVL trees keep balance factors in , , by rotations, with .
- In a 1-based heap the children of are and , and the parent is .
- Build-heap is , insert and delete-min are , and heap sort is and not stable.