Computer Science and IT‹›⌂ 0:00 studied

Module 5 · 18 min read · Free chapter

Trees, binary search trees and binary heaps

In short

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).

What are you preparing for? We show the practice and previous year questions of your exam.

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 00, and an empty tree has height −1-1. Some papers count levels from 11 instead, so always read the convention in the question. A tree with nn nodes always has exactly n−1n - 1 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 ii, with the root at level 00, holds at most 2i2^i nodes, because each level can at most double the one above.
  • A tree of height hh holds at most 1+2+⋯+2h=2h+1−11 + 2 + \dots + 2^h = 2^{h+1} - 1 nodes, which is reached by a perfect binary tree.
  • So nn nodes need height at least ⌈log⁡2(n+1)⌉−1\lceil \log_2(n+1) \rceil - 1, while the largest possible height is n−1n - 1, a chain.

Leaves and two-child nodes. Let n0n_0, n1n_1 and n2n_2 be the numbers of nodes with 00, 11 and 22 children. Counting edges two ways gives n1+2n2=n−1n_1 + 2n_2 = n - 1, and since n=n0+n1+n2n = n_0 + n_1 + n_2, we get

n0=n2+1n_0 = n_2 + 1

Worked example. A binary tree has 2020 nodes with two children and 1515 nodes with one child. Then it has n0=20+1=21n_0 = 20 + 1 = 21 leaves and 21+15+20=5621 + 15 + 20 = 56 nodes in all. Every node has two child pointers, so there are 2×56=1122 \times 56 = 112 pointers, of which 5555 are used by edges and 57=n+157 = n + 1 are NULL.

A full binary tree, in which every node has 00 or 22 children, is a special case with n1=0n_1 = 0. With II internal nodes it has I+1I + 1 leaves and 2I+12I + 1 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 log⁡2n\log_2 n 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 Θ(n)\Theta(n) 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 nn nodes? Pick which node is the root's left subtree size, say kk, and the right subtree then has n−1−kn - 1 - k nodes. Adding over all choices of kk gives the Catalan recurrence:

Cn=∑k=0n−1Ck⋅Cn−1−k,C0=1C_n = \sum_{k=0}^{n-1} C_k \cdot C_{n-1-k}, \qquad C_0 = 1

Its closed form is Cn=1n+1(2nn)C_n = \dfrac{1}{n+1}\binom{2n}{n}. For example, C3=14(63)=204=5C_3 = \dfrac{1}{4}\binom{6}{3} = \dfrac{20}{4} = 5 and C4=15(84)=705=14C_4 = \dfrac{1}{5}\binom{8}{4} = \dfrac{70}{5} = 14.

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 nn 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 nn keys is also CnC_n, and keys 1, 2 and 3 give 55 BSTs.

If the root must be key ii, then keys 11 to i−1i - 1 form the left subtree and keys i+1i + 1 to nn form the right one. So the number of BSTs with root ii is Ci−1⋅Cn−iC_{i-1} \cdot C_{n-i}. With n=5n = 5 and root 33 this is C2⋅C2=2×2=4C_2 \cdot C_2 = 2 \times 2 = 4.

Labelled trees. If the nn nodes carry distinct labels with no ordering rule, each shape can be labelled in n!n! ways. So there are Cn⋅n!C_n \cdot n! labelled binary trees, which is 5×6=305 \times 6 = 30 for n=3n = 3.

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 C6=132C_6 = 132 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:

  1. A leaf, such as 20, is simply removed.
  2. A node with one child is replaced by that child; after 20 is gone, deleting 30 lifts 40 into its place.
  3. 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 Θ(h)\Theta(h) time for height hh. A random BST has height about log⁡2n\log_2 n, but inserting keys in sorted order, such as 10, 20, 30, 40, builds a chain of height n−1n - 1, 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 11; this difference is the balance factor, which must be −1-1, 00 or 11. That one rule keeps the height at Θ(log⁡n)\Theta(\log n), so search, insert and delete all stay Θ(log⁡n)\Theta(\log n) in the worst case.

After an insertion, walk back up towards the root and find the first node whose balance factor has become 22 or −2-2. 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 11 and an empty left subtree of height −1-1, so its balance is −2-2, 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 N(h)N(h) be the fewest nodes in an AVL tree of height hh. The thinnest tree has one subtree of height h−1h - 1 and the other of height h−2h - 2, so

N(h)=N(h−1)+N(h−2)+1,N(0)=1, N(1)=2N(h) = N(h-1) + N(h-2) + 1, \qquad N(0) = 1,\ N(1) = 2

This gives N(2)=4N(2) = 4, N(3)=7N(3) = 7, N(4)=12N(4) = 12 and N(5)=20N(5) = 20. These numbers grow like Fibonacci numbers, which is exactly why the height is logarithmic in nn.

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 N(h)N(h) 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 11, node ii has children 2i2i and 2i+12i + 1 and parent ⌊i2⌋\lfloor \dfrac{i}{2} \rfloor; with indices from 00, as in C, the children are 2i+12i + 1 and 2i+22i + 2. A heap of nn keys has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, and its leaves occupy indices ⌊n2⌋+1\lfloor \dfrac{n}{2} \rfloor + 1 to nn.

Heapify (sift down). If both subtrees of node ii are heaps but node ii 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 O(log⁡n)O(\log n).

Build-heap. To turn an arbitrary array into a heap, call heapify on indices ⌊n2⌋\lfloor \dfrac{n}{2} \rfloor down to 11, since the leaves are already heaps. Take the array 9, 5, 8, 2, 4, 7, 1 with n=7n = 7:

  • 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 nn calls of O(log⁡n)O(\log n) each, but most nodes are near the bottom and sink very little. About n2h+1\dfrac{n}{2^{h+1}} nodes have height hh, so the total work is

∑h=0⌊log⁡2n⌋n2h+1⋅O(h)=O(n)\sum_{h=0}^{\lfloor \log_2 n \rfloor} \frac{n}{2^{h+1}} \cdot O(h) = O(n)

So bottom-up build-heap runs in Θ(n)\Theta(n), which beats inserting the keys one by one in O(nlog⁡n)O(n \log n).

Insert and delete-min. To insert, place the new key at index n+1n + 1 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 Θ(log⁡n)\Theta(\log n), and reading the minimum costs Θ(1)\Theta(1).

Repeating delete-min nn times outputs the keys in sorted order, and this is heap sort: Θ(nlog⁡n)\Theta(n \log n) 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:

  1. They ask you to define tree terms and prove a counting fact, such as n0=n2+1n_0 = n_2 + 1.
  2. They ask you to construct a tree from two traversals or from a sequence of BST insertions, and to traverse it.
  3. They ask you to explain BST deletion with all three cases, or AVL rotations with a figure for each case.
  4. 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).

  1. Prove that in any binary tree the number of leaves is one more than the number of nodes with two children. (10 marks)
  2. 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)
  3. 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 hh can sink at most hh levels, and that about n2h+1\dfrac{n}{2^{h+1}} nodes have height hh.
  • Add these costs as ∑n2h+1⋅h\sum \dfrac{n}{2^{h+1}} \cdot h and state that the series is at most nn times a constant, so the total is O(n)O(n).
  • Conclude that inserting the keys one by one costs O(nlog⁡n)O(n \log n), so the bottom-up method is better, and mention its use in heap sort.

Quick revision

  • A tree with nn nodes has n−1n - 1 edges, and here a single node has height 00.
  • A binary tree of height hh has at most 2h+1−12^{h+1} - 1 nodes, and every binary tree has n0=n2+1n_0 = n_2 + 1.
  • 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 Cn=1n+1(2nn)C_n = \dfrac{1}{n+1}\binom{2n}{n} shapes and BSTs on nn keys: 1, 1, 2, 5, 14, 42, 132.
  • BST operations cost Θ(h)\Theta(h), which is Θ(n)\Theta(n) 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 −1-1, 00, 11 by rotations, with N(h)=N(h−1)+N(h−2)+1N(h) = N(h-1) + N(h-2) + 1.
  • In a 1-based heap the children of ii are 2i2i and 2i+12i + 1, and the parent is ⌊i2⌋\lfloor \dfrac{i}{2} \rfloor.
  • Build-heap is Θ(n)\Theta(n), insert and delete-min are Θ(log⁡n)\Theta(\log n), and heap sort is Θ(nlog⁡n)\Theta(n \log n) and not stable.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. A tree with nn nodes has how many edges?

  2. The largest number of nodes in a binary tree of height hh (single node has height 00) is:

  3. A binary tree has 2020 nodes with two children. How many leaves does it have?

  4. Which traversal of a binary search tree lists its keys in sorted order?

  5. Preorder is A B D E C F and inorder is D B E A F C. The postorder is:

  6. Which pair of traversals may FAIL to fix a binary tree with distinct keys?

  7. How many distinct binary search trees can be built on the keys 1, 2, 3, 4?

  8. On keys 1 to 5, how many distinct BSTs have the key 3 at the root?

  9. The worst-case time to search a plain BST of nn keys is:

  10. In the BST built by inserting 50, 30, 70, 20, 40, 60, 80, the root 50 is deleted using its inorder successor. The new root is:

  11. With N(h)=N(h−1)+N(h−2)+1N(h) = N(h-1) + N(h-2) + 1, N(0)=1N(0) = 1, N(1)=2N(1) = 2, the fewest nodes in an AVL tree of height 44 is:

  12. In a binary heap stored from index 11, the children of node ii are at:

  13. Bottom-up build-heap on an array of nn elements takes:

  14. Build-heap (min-heap) is run on 9, 5, 8, 2, 4, 7, 1. The resulting array is:

  15. Finding the largest key in a min-heap of nn keys takes:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

How many distinct BSTs can be made with n keys?

The Catalan number Cₙ = (2n)! / ((n + 1)! n!), which is 5 for three keys and 14 for four keys.

Which traversals fix a binary tree uniquely?

Inorder together with preorder, postorder or level order does; preorder with postorder alone does not in general.

Why is build-heap Θ(n) and not Θ(n log n)?

Most nodes lie near the leaves and sink only a little, so the total sifting work adds up to a linear sum.

How is a BST node with two children deleted?

Copy in the key of its inorder successor, the smallest key in the right subtree, and then delete that successor node.

More in this module: Data structures

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): trees, binary search trees, heaps