Programming & DSA
Trees & Heaps
Trees and heaps are a must-score block: know the node-count formulas, trace traversals quickly, apply BST rules, and perform heap insert/delete on arrays.
GATE CSE trees and heaps — binary tree terminology, traversals, BST search/insert/delete, heap shape and heap property, array indexing, heap operations, and expression trees with samples and drills.
Learning outcomes
- Use binary tree terminology and counting formulas (levels, height, leaves vs degree-2 nodes) correctly
- Produce preorder, inorder, postorder, and level-order traversals and reconstruct trees from traversal pairs
- Search, insert, and delete in a BST and state the effect of tree height on cost
- Maintain a binary heap in an array, with insert, delete, and build-heap complexity, and relate expression trees to prefix/postfix
Binary tree terminology and counting
- A tree is a connected acyclic structure. In a rooted binary tree each node has at most two children (left, right). The root has no parent; a leaf has no children; internal nodes have at least one child.
- Depth (level) of a node = number of edges from the root (root depth 0). Height of a node = edges on the longest path down to a leaf; height of the tree = height of the root. A single node has height 0; an empty tree is conventionally −1. (If a question counts nodes instead, add 1 — always check the convention.)
- Maximum nodes at level i is 2^i. Maximum nodes in a binary tree of height h is 2^(h+1) − 1 (a perfect tree). The minimum height with n nodes is floor(log2 n); the maximum height is n − 1 (a skewed tree).
- In any binary tree with n nodes: edges = n − 1, and number of leaves n0 = (number of nodes with 2 children) n2 + 1. Nodes with one child do not affect this relation.
- A binary tree with n nodes has exactly n + 1 NULL child pointers.
- Full binary tree: every node has 0 or 2 children (so n is odd and leaves = (n + 1)/2). Complete binary tree: all levels full except possibly the last, which is filled left to right. Perfect binary tree: all internal nodes have 2 children and all leaves are at the same level.
- Number of structurally distinct binary trees with n nodes is the Catalan number (1/(n+1)) × C(2n, n): 1, 2, 5, 14 for n = 1, 2, 3, 4.
Formulas to remember
-
Nodes at level i ≤ 2^i; nodes in height-h tree ≤ 2^(h+1) − 1 -
Height ≥ floor(log2 n) -
n0 = n2 + 1; edges = n − 1; NULL pointers = n + 1 -
Binary trees with n nodes = C_n = (1/(n+1)) × C(2n, n)
Worked example
Problem. A binary tree has 10 nodes of which 4 have two children. How many leaves does it have?
Solution. n0 = n2 + 1 = 4 + 1 = 5 leaves (the remaining 1 node has exactly one child).
Tree traversals
- Inorder: Left, Node, Right (LNR). Preorder: Node, Left, Right (NLR). Postorder: Left, Right, Node (LRN). Level order: breadth-first using a queue. Each depth-first traversal runs in O(n) time and uses O(h) stack space.
- Preorder gives the root first, postorder gives the root last, and inorder splits the tree: everything left of the root in inorder belongs to the left subtree.
- A binary tree can be reconstructed uniquely from inorder + preorder or inorder + postorder. Preorder + postorder alone does not determine the tree in general (it does for full binary trees).
- Reconstruction method: the first preorder (or last postorder) element is the root; find it in inorder to split left and right parts; recurse.
- For a BST, the inorder traversal is the sorted order of keys. A BST is uniquely determined by its preorder (or postorder) sequence alone.
- Level order uses a queue: enqueue root; repeatedly dequeue, visit, and enqueue the children.
| Traversal | Order | Output for the sample tree |
|---|---|---|
| Preorder | N L R | A B D E C F |
| Inorder | L N R | D B E A C F |
| Postorder | L R N | D E B F C A |
| Level order | Level by level | A B C D E F |
Worked example
Problem. Sample tree: A is the root; A has left child B (children D, E) and right child C (with only a right child F). Verify the postorder.
Solution. Left subtree of A in postorder: D E B; right subtree: F C; then the root A. Postorder = D E B F C A.
Binary search trees (BST)
- BST property: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger (assuming distinct keys). Inorder traversal visits keys in ascending order.
- Search, insert, and delete cost O(h), where h is the height. For a balanced tree h = O(log n); for a skewed tree (inserting sorted keys) h = n − 1 and the cost is O(n).
- Minimum key: keep going left. Maximum key: keep going right. Inorder successor of a node with a right subtree is the minimum of that subtree.
- Insert: search for the key; the new node becomes a leaf at the NULL position where the search ended. Insertion order decides the shape: keys 10, 20, 30 give a right-skewed chain; 20, 10, 30 give a balanced tree.
- Delete: leaf → remove; one child → replace the node by its child; two children → replace the key with its inorder successor (min of right subtree) or predecessor, then delete that node (which has at most one child).
- The number of distinct BSTs with n distinct keys is the Catalan number: 5 for n = 3, 14 for n = 4.
- AVL tree: BST in which every node has balance factor (height of left − height of right) in {−1, 0, 1}, so h = O(log n). The minimum nodes N(h) in an AVL tree of height h satisfy N(h) = N(h−1) + N(h−2) + 1 with N(0) = 1 and N(1) = 2: 1, 2, 4, 7, 12, ...
| BST operation | Balanced tree | Skewed tree |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Find min / max | O(log n) | O(n) |
Worked example
Problem. Insert 50, 30, 70, 20, 40, 60, 80 into an empty BST. What is the height (in edges) and the inorder output?
Solution. The tree is perfect: height 2. Inorder: 20 30 40 50 60 70 80.
Binary heaps
- A binary heap is a complete binary tree that satisfies the heap property: in a max-heap every parent ≥ its children (the maximum is at the root); in a min-heap every parent ≤ its children (the minimum is at the root). There is no ordering between siblings.
- Array representation with 1-based indices: parent of i is floor(i/2); left child is 2i; right child is 2i + 1. With 0-based indices: parent (i − 1)/2 (integer division), children 2i + 1 and 2i + 2.
- Height of a heap with n nodes is floor(log2 n). Leaves occupy indices floor(n/2) + 1 to n, so the number of leaves is ceil(n/2) and internal nodes are floor(n/2).
- Insert: place the new key in the first free position (end of array) and sift up (swap with parent while the heap property is violated) — O(log n).
- Delete-max (extract root): move the last element to the root, shrink the array, and sift down (swap with the larger child in a max-heap) — O(log n).
- Build-heap by calling heapify on nodes floor(n/2) down to 1 takes O(n) (not O(n log n)). Heapsort = build-heap + n extractions = O(n log n) time, O(1) extra space.
- Searching for an arbitrary key in a heap is O(n). In a max-heap the minimum is among the leaves. Priority queues are implemented with heaps.
Formulas to remember
-
1-based: parent(i) = ⌊i/2⌋, left(i) = 2i, right(i) = 2i + 1 -
0-based: parent(i) = ⌊(i−1)/2⌋, left(i) = 2i + 1, right(i) = 2i + 2 -
Height = ⌊log2 n⌋; leaves = ⌈n/2⌉
Worked example
Problem. Max-heap array [50, 30, 40, 10, 20]. Insert 60.
Solution. 60 goes to index 6, parent index 3 (40): swap → [50,30,60,10,20,40]; parent index 1 (50): swap → [60,30,50,10,20,40].
Expression trees
- An expression tree has operands as leaves and operators as internal nodes. For binary operators, an expression with n operands has n − 1 operators and 2n − 1 nodes in total.
- Inorder traversal gives the infix form (parentheses are needed to retain the structure), preorder gives the prefix form, and postorder gives the postfix form.
- Evaluate by postorder: evaluate the left subtree, the right subtree, and then apply the operator at the node. The tree directly encodes precedence and associativity.
- Building the tree from postfix: scan left to right; push a one-node tree for each operand; for an operator pop two trees (right first, then left) and make them the children of a new operator node.
- Two expressions are structurally the same if their trees are equal; common subexpressions appear as repeated subtrees (shared in a DAG).
- Expression trees are full binary trees: every internal node has exactly two children for binary operators.
| Expression | Tree root | Postfix | Prefix |
|---|---|---|---|
| (a + b) * (c − d) | * | a b + c d − * | * + a b − c d |
| a + b * c | + | a b c * + | + a * b c |
| (a + b) * c | * | a b + c * | * + a b c |
Worked example
Problem. Expression tree: root *, left child + (leaves a, b), right child − (leaves c, d). Give the postorder traversal.
Solution. Left subtree postorder: a b +; right subtree: c d −; then the root: a b + c d − *.
GATE exam tricks — trees, BSTs and heaps
- Reconstruction recipe: preorder (or postorder) gives the root; locate it in inorder; everything left of it is the left subtree, right of it the right subtree; recurse. Preorder + postorder alone does NOT determine a tree unless every node has 0 or 2 children.
- Counting: n unlabeled nodes give Catalan C_n distinct binary tree shapes and also C_n distinct BSTs on n keys. n0 = n2 + 1 and NULL pointers = n + 1 in any binary tree.
- BST insert order controls the shape: sorted input gives a skewed tree of height n - 1; inserting the median first gives a balanced tree. Preorder of a BST alone uniquely rebuilds it.
- BST deletion with two children: replace the key with its inorder successor (smallest in the right subtree) or predecessor (largest in the left subtree), then delete that node.
- Inorder of a BST is sorted ascending; to check a BST validly, test against ancestor bounds, not just immediate children.
- Heap facts: leaves are at indices floor(n/2)+1..n; the minimum of a max-heap is in a leaf; the number of nodes at height h is at most ceil(n / 2^(h+1)); build-heap is O(n) but n successive inserts is O(n log n).
- Heap array validity: for every i check A[i] >= A[2i] and A[2i+1] (max-heap, 1-indexed). One bad parent-child pair anywhere invalidates the whole array.
- AVL: balance factor = height(left) - height(right) must be in {-1, 0, 1}. Minimum nodes N(h) = N(h-1) + N(h-2) + 1 with N(0) = 1, N(1) = 2, giving 1, 2, 4, 7, 12, 20 for h = 0..5.
- Always state whether height counts edges or nodes before using a formula; the final answer differs by 1.
Worked example
Problem. Preorder: 1 2 4 5 3 and Inorder: 4 2 5 1 3. What is the postorder?
Solution. Root = 1 (first in preorder). Inorder splits as (4 2 5) | 3. In the left part the preorder is 2 4 5, so 2 is the subtree root with left 4 and right 5. Right subtree is just 3. Postorder = left, right, root = 4 5 2 3 1.
Worked trace: heap insert and delete-max
- Insert: append at index n + 1, then swap with the parent while the child is larger (max-heap). At most height swaps.
- Delete-max: move the last element to index 1, decrease n, then swap with the LARGER child until the heap property holds.
- Always redraw both the tree and the array; a swap in one must be mirrored in the other.
Worked example
Problem. Max-heap array (1-indexed) [90, 70, 80, 40, 50, 60]. Insert 85, then perform one delete-max. Give the final array.
Solution. Insert 85 at index 7 (parent index 3 holds 80): 85 > 80 so swap, giving [90, 70, 85, 40, 50, 60, 80]; parent index 1 is 90 >= 85, stop. Delete-max: remove 90, move last (80) to the root: [80, 70, 85, 40, 50, 60]. Larger child of the root is 85, swap: [85, 70, 80, 40, 50, 60]. Index 3 now has child 60 only (index 6); 80 >= 60, stop. Final: [85, 70, 80, 40, 50, 60].
Exam tips
- State the height convention (edges vs nodes) before using 2^(h+1) − 1 or similar formulas.
- For reconstruction, find the root from preorder/postorder, split inorder around it, and recurse.
- BST inorder is sorted; BST cost is O(h), not O(log n) unless balanced.
- Heap questions: always draw the array and compute parent/child indices from the base given (0 or 1).
- Build-heap is O(n); heapsort is O(n log n); search in a heap is O(n).
10 GATE-style MCQs for Trees & Heaps with full explanations. Attempt each question before revealing the answer.
The maximum number of nodes in a binary tree of height 4 (a single-node tree has height 0) is:
Show answer & explanation
Answer: C
Maximum nodes = 2^(h+1) − 1 = 2^5 − 1 = 31.
A binary tree has 10 nodes, and 4 of them have exactly two children. The number of leaves is:
Show answer & explanation
Answer: B
In any binary tree, leaves = (nodes with two children) + 1 = 4 + 1 = 5.
Keys 15, 10, 20, 8, 12, 25 are inserted in this order into an empty BST. The inorder traversal is:
Show answer & explanation
Answer: B
Inorder traversal of a BST lists the keys in ascending order.
The preorder traversal of a BST is 5 3 1 4 8 7 9. Its postorder traversal is:
Show answer & explanation
Answer: A
The BST has root 5, left subtree 3 (children 1, 4), right subtree 8 (children 7, 9). Postorder: left subtree 1 4 3, right subtree 7 9 8, then 5.
A min-heap is stored as the array [2, 5, 3, 9, 6] (1-based). After inserting 1 the array becomes:
Show answer & explanation
Answer: B
1 is placed at index 6; its parent (index 3, value 3) is larger, so swap; then its parent (index 1, value 2) is larger, so swap again: [1, 5, 2, 9, 6, 3].
In a binary heap stored in a 0-indexed array, the children of the node at index 4 are at indices:
Show answer & explanation
Answer: B
For 0-based indexing, the children of i are 2i + 1 = 9 and 2i + 2 = 10.
The height of a binary heap with 1000 nodes (single-node height 0) is:
Show answer & explanation
Answer: B
Height = floor(log2 1000) = 9, since 2^9 = 512 ≤ 1000 < 1024 = 2^10.
How many leaves does a binary heap with 11 nodes have?
Show answer & explanation
Answer: B
Internal nodes = floor(11/2) = 5, so leaves = 11 − 5 = 6 (indices 6 to 11).
The expression tree has root *, left child + with leaves a and b, and right child − with leaves c and d. Its postorder traversal is:
Show answer & explanation
Answer: B
Postorder = left, right, root: (a b +) (c d −) * = a b + c d − *.
How many structurally distinct binary search trees can be formed with 3 distinct keys?
Show answer & explanation
Answer: B
The count is the Catalan number C3 = (1/4) × C(6,3) = 20/4 = 5.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
The preorder of a binary tree is A B D E C F and its inorder is D B E A C F. The postorder is:
Show answer & explanation
Answer: A) D E B F C A
Root A; left subtree B (D, E); right subtree C with right child F. Postorder: D E B, F C, A.
The height (in edges) of a complete binary tree with 15 nodes is:
Show answer & explanation
Answer: A) 3
15 = 2^4 − 1 nodes form a perfect tree of height 3; also floor(log2 15) = 3.
The number of NULL child pointers in a binary tree with 7 nodes is:
Show answer & explanation
Answer: C) 8
A binary tree with n nodes has n + 1 NULL pointers: 7 + 1 = 8.
In a BST the minimum key is found at:
Show answer & explanation
Answer: C) The leftmost node
Following left children from the root reaches the smallest key.
Keys 5, 3, 8, 1, 4 are inserted into an empty BST. The height of the tree in edges is:
Show answer & explanation
Answer: B) 2
Root 5; children 3 and 8; 1 and 4 are children of 3. The longest path 5 → 3 → 1 has 2 edges.
In a max-heap, the largest element is located at:
Show answer & explanation
Answer: B) The root
Every parent is at least as large as its children, so the root holds the maximum.
The worst-case time complexity of heapsort on n elements is:
Show answer & explanation
Answer: B) O(n log n)
Build-heap costs O(n) and n extract-max operations cost O(log n) each.
The max-heap [50, 30, 40, 10, 20] (1-based) has its maximum deleted. The resulting heap array is:
Show answer & explanation
Answer: A) 40 30 20 10
Move the last element 20 to the root: [20,30,40,10]; swap with the larger child 40: [40,30,20,10].
Keys 1, 2, 3, 4, 5 are inserted in this order into an empty BST. The height in edges is:
Show answer & explanation
Answer: C) 4
Each key becomes the right child of the previous one, creating a chain with 4 edges.
For build-heap on 15 elements, how many internal nodes must be heapified?
Show answer & explanation
Answer: C) 7
Heapify is applied to nodes floor(15/2) = 7 down to 1, i.e. 7 internal nodes.
Topic FAQs
Why is the relation n0 = n2 + 1 true?
Counting edges two ways: edges = n − 1 = n1 + 2 × n2 and n = n0 + n1 + n2, which simplifies to n0 = n2 + 1.
Is the heap array sorted?
No. A heap only guarantees parent-child ordering; sibling order and cross-subtree order are not constrained.
Why is build-heap O(n) and not O(n log n)?
Most nodes are near the leaves and sift down only a few levels; the sum of the heights over all nodes is O(n).
Can a BST degenerate into a linked list?
Yes. Inserting keys in sorted order produces a skewed tree of height n − 1, making search, insert, and delete O(n); self-balancing trees such as AVL prevent this.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.