IAE Academy

GATE CS · DA

Trees, binary search trees and binary heaps

Trees, binary search trees and binary heaps: how hierarchical data is structured, searched and prioritised. These notes cover counting results for binary trees (node bounds, , Catalan numbers) and rebuilding a tree from its traversals. They also cover BST search, insert and delete, AVL balance and rotations, and binary heaps: array layout, sift-up and sift-down, build-heap and heap sort. Throughout, the height of a tree is counted in edges: a single node has height 0 and an empty tree has height .

26 previous-year questions · 24 solved · 7 practice questions

Binary trees: structure and counting properties

A binary tree is a rooted tree in which every node has at most two children, distinguished as left and right. Convention used throughout these notes: the height of a tree is the number of edges on the longest root-to-leaf path. A single-node tree has height 0 and an empty tree has height . The depth (or level) of a node is the number of edges from the root to it, so the root is at level 0. Some questions count height or level in nodes instead of edges, with the root at level 1. That shifts every height- and level-based formula below by 1, so always check the convention a question states.

MAXIMUM NODES AT A GIVEN LEVEL

Root at level 0. An upper bound for any binary tree, reached exactly when level is completely filled.

MAXIMUM NODES IN A TREE OF GIVEN HEIGHT

Reached exactly by a perfect binary tree of height (every level completely filled).

MINIMUM NODES IN A TREE OF GIVEN HEIGHT

Reached by any tree with exactly one node per level: left-skewed, right-skewed or zig-zag.

HEIGHT RANGE FOR N NODES

The lower bound follows from . A complete binary tree with nodes, and so every binary heap, has height exactly .

LEAVES VERSUS NODES WITH TWO CHILDREN (ANY BINARY TREE)

Holds for every non-empty binary tree, whatever the number of one-child nodes. Here = leaves and = nodes with two children. Proof: count edges two ways. With nodes there are edges, and each edge hangs below exactly one parent, so . Subtracting gives .

FULL (STRICT) BINARY TREE: LEAVES, INTERNAL NODES, TOTAL

In a full binary tree every node has 0 or 2 children, so . With internal nodes it has leaves and nodes in all (always odd). More generally, a full -ary tree (every node has 0 or children) with internal nodes has leaves.

Special shapes you must be able to recognise on sight

  1. Full / proper / strict binary tree: every node has exactly 0 or 2 children, never exactly 1.

  2. Complete binary tree: every level is completely filled except possibly the last, and the last level's nodes are as far left as possible, with no gaps. This is exactly the shape a binary heap's array stores.

  3. Perfect binary tree: every internal node has 2 children AND every leaf is at the same level. A perfect tree of height has nodes, of which are leaves and are internal.

  4. Height-balanced tree: at every node, the heights of the left and right subtrees differ by at most a fixed bound (for AVL trees, at most 1). Balance limits the worst-case height, not the node count.

EXAM TIP

Terminology varies. Some texts use 'complete binary tree' for what these notes call perfect, and 'almost complete' for what these notes call complete. Use the definition the question gives. A complete tree need not have all leaves on one level; only the last level must be filled from the left. Sanity check: a tree with nodes always has exactly edges.

Tree traversals and reconstruction

The four standard traversals

  1. Preorder: visit the root, then traverse the left subtree, then the right subtree (root, left, right).

  2. Inorder: traverse the left subtree, visit the root, then traverse the right subtree (left, root, right). On a BST this visits the keys in increasing order.

  3. Postorder: traverse the left subtree, then the right subtree, then visit the root (left, right, root).

  4. Level-order (BFS): visit nodes level by level, left to right within a level. It is implemented with a queue: enqueue the root, then repeatedly dequeue a node, visit it and enqueue its non-null children.

Rebuilding a unique tree from traversals (all keys distinct):

  • Inorder + preorder or inorder + postorder determines the binary tree uniquely. Take the root from the preorder (first element) or the postorder (last element), find it in the inorder sequence to split the left and right subtrees, and recurse.
  • Inorder + level-order also determines it uniquely.
  • Preorder + postorder does NOT determine a general binary tree. If a node has a single child, that child can be its left or its right child without changing either sequence. If the tree is known to be full (every node has 0 or 2 children), preorder + postorder do determine it.
  • For a BST, one traversal is enough, because its inorder sequence is just the keys sorted. Equivalently, inserting the keys into an empty BST in preorder order, in level order, or in reverse postorder order rebuilds the same tree. Each of these orders lists every parent before its children.

WORKED EXAMPLE

A binary tree has inorder traversal D B E A F C G and preorder traversal A B D E C F G. Rebuild the tree and give its postorder traversal.

Solution
  1. Root = first element of the preorder = A.

  2. Split the inorder at A: left = D B E, right = F C G (3 nodes each).

  3. Split the rest of the preorder, B D E C F G, by those sizes: left preorder = B D E, right preorder = C F G.

  4. Left subtree (inorder D B E, preorder B D E): the root is B. The inorder splits into D | B | E, so B's left child is D and its right child is E.

  5. Right subtree (inorder F C G, preorder C F G): the root is C. The inorder splits into F | C | G, so C's left child is F and its right child is G.

  6. The tree is A(left = B(left = D, right = E), right = C(left = F, right = G)).

  7. Postorder (left, right, root): B's subtree gives D, E, B; C's subtree gives F, G, C; then the root A.

Answer: Postorder = D E B F G C A

These traversal functions assume a node with data, left and right fields. Code-tracing questions are built on this pattern.

#include <stdio.h>

struct Node {
    int data;
    struct Node *left, *right;
};

void preorder(struct Node *root) {
    if (root == NULL) return;
    printf("%d ", root->data);
    preorder(root->left);
    preorder(root->right);
}

void inorder(struct Node *root) {
    if (root == NULL) return;
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

void postorder(struct Node *root) {
    if (root == NULL) return;
    postorder(root->left);
    postorder(root->right);
    printf("%d ", root->data);
}

Trace of the preorder function on the tree from the worked example (letters stand for the stored values):

  • preorder(A) prints A, then calls preorder(B).
  • preorder(B) prints B, then calls preorder(D). D is a leaf: it prints D, and both of its recursive calls get NULL and return at once.
  • Back in B, preorder(E) prints E. B's call then returns to A.
  • A calls preorder(C), which prints C, then F (leaf), then G (leaf).

Output: A B D E C F G, the given preorder, which confirms the rebuilt tree. The same tree gives inorder D B E A F C G and postorder D E B F G C A.

Binary search trees (BST)

A binary search tree on distinct keys satisfies, at every node: every key in the left subtree is smaller than the node's key, and every key in the right subtree is larger. Search, insert and delete therefore each follow one comparison-guided path down from the root, so each costs time, where is the current height. The tree's shape, and so , depends on the order in which the keys were inserted.

BST operations

  1. Search(key): start at the root. If the key equals the current node's key, it is found. If it is smaller, go left; if larger, go right. Reaching NULL means the key is absent.

  2. Insert(key): search for the key as above until you reach NULL, then attach a new leaf holding the key at that spot.

  3. Delete(key) has three cases. (1) The node is a leaf: remove it. (2) The node has exactly one child: link that child directly to the node's parent in its place. (3) The node has two children: copy into it the key of its inorder successor, the minimum of its right subtree (go right once, then left as far as possible). Then delete the successor from its old position. The successor has no left child, so that deletion is case 1 or case 2. Alternatively use the inorder predecessor, the maximum of the left subtree. The two choices give different trees, and a question will say which one it uses.

BST HEIGHT FOR N KEYS

The lower bound holds when the tree is complete. The upper bound is a chain, and every operation then costs in the worst case. Sorted or reverse-sorted input gives a chain, but so do other orders, such as 1, 5, 2, 4, 3. Of the insertion orders of distinct keys, exactly give height . When all insertion orders are equally likely, the expected height is .

Recursive BST insert in C:

#include <stdlib.h>

struct Node* insert(struct Node *root, int key) {
    if (root == NULL) {
        struct Node *n = malloc(sizeof(struct Node));
        n->data = key;
        n->left = n->right = NULL;
        return n;
    }
    if (key < root->data)
        root->left = insert(root->left, key);
    else if (key > root->data)
        root->right = insert(root->right, key);
    /* key == root->data: a duplicate, ignored (keys assumed distinct) */
    return root;
}

Trace: inserting 40, 20, 60, 10, 30 in that order makes 40 the root, with 20 on its left and 60 on its right. Then 10 becomes the left child of 20 and 30 its right child. The height is 2: this order does not produce a chain.

WORKED EXAMPLE

Keys 50, 30, 70, 20, 40, 60, 80 are inserted in that order into an empty BST. Then 50 is deleted, replacing it with its inorder successor. What does the tree look like afterwards?

Solution
  1. After the insertions: root 50 has left child 30 (children 20 and 40) and right child 70 (children 60 and 80), a perfect tree of height 2.

  2. 50 has two children, so this is case 3. Its inorder successor is the minimum of the right subtree: go right to 70, then left to 60. 60 has no left child, so 60 is the successor.

  3. Copy 60 into the root, then delete the old 60. It is a leaf (case 1), so 70 loses its left child.

  4. Check: the inorder is 20 30 40 60 70 80, which is sorted, so the tree is still a BST.

Answer: Root 60; left subtree 30 (20, 40); right subtree 70 with only a right child, 80. Using the inorder predecessor instead would give root 40, with 30 keeping only its left child 20.

EXAM TIP

BST search, insert and delete are all . They are in the worst case only for balanced search trees such as AVL or red-black trees, which keep . Never assume a plain BST is balanced unless the question says so.

AVL trees: self-balancing BSTs

An AVL tree is a BST that restores one extra rule after every insertion and deletion: at every node, the heights of the left and right subtrees differ by at most 1. This keeps the height , so search, insert and delete each take time in the worst case.

BALANCE FACTOR

An AVL tree needs at every node, with the height of an empty subtree taken as . A node whose BF becomes or after an update must be rebalanced by rotation.

MINIMUM NODES IN AN AVL TREE OF HEIGHT H

The sparsest AVL tree of height is a root whose two subtrees are sparsest AVL trees of heights and . This gives and in closed form , where are the Fibonacci numbers. Consequently an AVL tree with nodes has height , which is . The maximum number of nodes of height is , as for any binary tree.

Rotation cases after an insertion (z = the lowest unbalanced ancestor of the new node)

Case

Where the new node went

Fix

Left-Left (LL)

Left subtree of z's left child

Single right rotation at z

Right-Right (RR)

Right subtree of z's right child

Single left rotation at z

Left-Right (LR)

Right subtree of z's left child

Left rotation at z's left child, then right rotation at z

Right-Left (RL)

Left subtree of z's right child

Right rotation at z's right child, then left rotation at z

WORKED EXAMPLE

Insert 30, 10, 20 in that order into an empty AVL tree. Show the rebalancing.

Solution
  1. Insert 30: the root. Insert 10: the left child of 30. Insert 20: it is smaller than 30 and larger than 10, so it becomes the right child of 10.

  2. Heights: 20 has height 0; 10 has height 1 (left empty, height ), so BF(10) = ; 30 has height 2, with BF(30) = . The lowest unbalanced node is z = 30.

  3. The new node is in the right subtree of z's left child: the LR case.

  4. Left rotation at 10: 20 takes 10's place as the left child of 30, with 10 as 20's left child.

  5. Right rotation at 30: 20 becomes the root, with left child 10 and right child 30. All balance factors are now 0.

Answer: Root 20, left child 10, right child 30 (height 1)

EXAM TIP

After one insertion, rebalancing the lowest unbalanced ancestor with a single or double rotation restores the height that subtree had before the insertion, so every ancestor above it is balanced again. At most one rotation (single or double) is needed per insertion. Deletion is different: a rotation can reduce a subtree's height and unbalance an ancestor further up, so one deletion may need a rotation at each level up to the root, which is rotations.

Binary heaps

A binary heap is a complete binary tree stored in an array with no pointers, which obeys the heap-order property. In a max-heap every parent's key is each of its children's keys, so the maximum is at the root. A min-heap reverses the inequality. Heap order says nothing about left versus right: unlike in a BST, siblings and cousins can be in any relative order.

Array representation

  1. 0-indexed: the node at index has its left child at , its right child at (when within bounds) and its parent at for .

  2. 1-indexed: the node at index has its children at and and its parent at . Check which convention a question uses before computing any index.

  3. Any array, read level by level, is a complete binary tree. Whether it is a heap depends only on the heap-order checks between each parent and its children.

HEIGHT, LEAVES AND INTERNAL NODES OF AN N-ELEMENT HEAP

In the 1-indexed layout the leaves are at indices to ; in the 0-indexed layout at to . In a max-heap with distinct keys the minimum is always at a leaf, since an internal node has a smaller child, and it can be at any leaf. Finding it therefore means scanning the leaves, which is .

BUILD-HEAP RUNNING TIME

Bottom-up build-heap calls sift-down (heapify) on every internal node, from the last one back to the root. An -element heap has at most nodes at height , and sifting one down costs . The total is , because . It is linear, NOT . Building by successive inserts instead costs in the worst case.

HEAP SORT

Build a max-heap in . Then times: swap the root with the last element of the heap, shrink the heap by 1 and sift down the new root, each costing . It sorts in place and is not stable. auxiliary space assumes an iterative sift-down; the recursive maxHeapify below uses stack space.

Cost of binary max-heap operations (n elements, worst case)

Operation

Cost

Find max

Insert

Extract max (delete root)

Increase key / delete the element at a known index

Search for an arbitrary key; find min

Build-heap (bottom-up)

successive inserts into an empty heap

Merge two heaps of sizes and (concatenate, then build-heap)

Insert and delete-max procedures (max-heap)

  1. Insert(key): put the key in the next free array slot, the end of the complete tree. Then sift up: while it is not the root and is greater than its parent, swap it with its parent. Worst case .

  2. Delete-max (extract-max): save the root's value as the answer. Move the LAST element of the array into the root and shrink the heap by 1. Then sift down the new root: while it has a child larger than itself, swap it with the larger of its children. Worst case .

Sift-down (max-heapify) and build-heap in C, 0-indexed:

void maxHeapify(int a[], int n, int i) {
    int largest = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;
    if (l < n && a[l] > a[largest]) largest = l;
    if (r < n && a[r] > a[largest]) largest = r;
    if (largest != i) {
        int t = a[i];
        a[i] = a[largest];
        a[largest] = t;
        maxHeapify(a, n, largest);
    }
}

void buildMaxHeap(int a[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--)
        maxHeapify(a, n, i);
}

WORKED EXAMPLE

Build a max-heap (0-indexed) from the array [4, 10, 3, 5, 1, 15] with bottom-up build-heap.

Solution
  1. , so the last internal node is at index . maxHeapify runs for in that order; the leaves at indices 3, 4, 5 need no work.

  2. (value 3): the left child is at index 5 (value 15); the right child, index 6, is out of range. 15 > 3, so swap: [4, 10, 15, 5, 1, 3]. Index 5 is a leaf, so stop.

  3. (value 10): the children are at index 3 (value 5) and index 4 (value 1). 10 is the largest of the three: no swap.

  4. (value 4): the children are at index 1 (value 10) and index 2 (value 15). The largest is 15, so swap: [15, 10, 4, 5, 1, 3]. Continue at index 2 (value 4): its only child is at index 5 (value 3), and 4 > 3, so stop.

Answer: Max-heap array: [15, 10, 4, 5, 1, 3]

WORKED EXAMPLE

Perform one extract-max on the max-heap [15, 10, 4, 5, 1, 3] (0-indexed).

Solution
  1. Save the root, 15, as the answer. Move the last element, 3, to the root and shrink the heap to 5 elements: [3, 10, 4, 5, 1].

  2. Sift down from index 0 (value 3): the children are 10 (index 1) and 4 (index 2). The larger is 10, and 10 > 3, so swap: [10, 3, 4, 5, 1].

  3. Continue at index 1 (value 3): the children are 5 (index 3) and 1 (index 4). The larger is 5, and 5 > 3, so swap: [10, 5, 4, 3, 1].

  4. Index 3 is a leaf, so stop. Check: 10 ≥ 5, 4; 5 ≥ 3, 1.

Answer: Returns 15; the heap becomes [10, 5, 4, 3, 1]

EXAM TIP

Build-heap must process nodes bottom-up, from the last internal node back to the root. A single top-down pass, running sift-down from index 0 forwards, does NOT produce a heap in general. Building by successive inserts does give a valid heap, but it may be a different array from the one bottom-up build-heap gives, so follow the method the question names.

Counting binary trees and BSTs: Catalan numbers

The number of different binary tree shapes with nodes equals the number of different BSTs on distinct keys. Once the shape is fixed, the BST property forces the sorted keys into its positions in inorder order, so each shape carries exactly one BST. Both counts are the -th Catalan number.

CATALAN NUMBER

The recurrence chooses the root's left subtree size ; the right subtree then has nodes. The first values are . is the number of binary tree shapes with nodes and the number of BSTs on distinct keys. It also counts the ways to fully parenthesise a product of factors, and the balanced bracket strings of length . If distinct labels may be placed freely in the nodes (no BST rule), the number of labelled binary trees is .

WORKED EXAMPLE

How many different binary tree shapes have exactly 3 nodes?

Solution
  1. .

  2. Check by listing them. One shape has a root with two leaf children. In the other four the root has a single 2-node subtree: that subtree can be on the left or the right, and it has 2 shapes of its own. These four are the two straight chains (left-left, right-right) and the two zig-zags (left-right, right-left). That makes . So 3 distinct keys give exactly 5 BSTs.

Answer: 5

PREVIOUS-YEAR QUESTIONS

26 questions from the CS and DA papers

Try each question first, then open the answer. 2 show the official answer only. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE CSE 2026 Set 1 · GATE CSE 2026 Set 2 · GATE CSE 2025 Set 1 · GATE CSE 2025 Set 2 · GATE CSE 2024 Set 1 · GATE CSE 2024 Set 2 · GATE CSE 2023 · GATE CSE 2022 · GATE CSE 2020 · GATE CSE 2018 · GATE DA 2026 · GATE DA 2024

GATE 2026 CS1 Q.40

GATE 2026 · CS1Q.40 · 2 marks · MCQ

Let be the set of all integers from 1 to 15. Consider any order of insertion of the elements of into a binary search tree that creates a complete binary tree.

Which one of the following elements can NEVER be the third element that is inserted?

  1. (A)

    4

  2. (B)

    2

  3. (C)

    10

  4. (D)

    5

Official answer
See the question in the paper
GATE 2026 CS1 Q.40: official answer

GATE 2026 CS2 Q.12

GATE 2026 · CS2Q.12 · 1 mark · MCQ

The set T represents various traversals over binary tree. The set S represents the order of visiting nodes during a traversal.

| T | S |
|---|---|
| I: Inorder | L: left subtree, node, right subtree |
| II: Preorder | M: node, left subtree, right subtree |
| III: Postorder | N: left subtree, right subtree, node |

Which one of the following is the correct match from T to S ?

GATE 2026 CS2 question 12: A two-column table with header row 'T' and 'S'.Tap to open full size
Figure from the GATE 2026 CS2 paper. It is part of the question.
Figure description

A two-column table with header row 'T' and 'S'. Three data rows: Row 1: 'I: Inorder' | 'L: left subtree, node, right subtree'. Row 2: 'II: Preorder' | 'M: node, left subtree, right subtree'. Row 3: 'III: Postorder' | 'N: left subtree, right subtree, node'.

  1. (A)

    I – L, II – M, III – N

  2. (B)

    I – M, II – L, III – N

  3. (C)

    I – N, II – M, III – L

  4. (D)

    I – L, II – N, III – M

Answer and solution
GATE 2026 CS2 Q.12: answer and solution

GATE 2026 CS2 Q.49

GATE 2026 · CS2Q.49 · 2 marks · MSQ

Consider a binary search tree (BST) with leaf nodes (). Given any node , the key present in the node is denoted as . All the keys present in the given BST are distinct. The keys belong to the set of real numbers.

For a node , let denote the node that is its inorder successor. If a node does not have an inorder successor, then is . As there are no duplicates, if is not , then .

Corresponding to every leaf node that has a non-NULL , a new key with the following property is to be inserted into the BST.

Let represent the list of all such new keys to be inserted into the BST.

Which of the following statements is/are true?

  1. (A)

    cannot have any duplicates

  2. (B)

    will have at least one element

  3. (C)

    After inserting all keys from , the height of the BST can increase at most by one

  4. (D)

    Number of nodes in the BST will double after inserting all keys from

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.49: answer and solution

GATE 2026 DA Q.25

GATE 2026 · DAQ.25 · 1 mark · MSQ

You are given the following Pre-order and In-order traversals of a Binary Tree T with nodes E, F, G, P, Q, R, S.

Pre-order: P Q S E R F G
In-order: S Q E P F R G

Which of the following statements is/are true about the Binary Tree T?

  1. (A)

    Node P is the root of T

  2. (B)

    The Post-order traversal of T is: S E Q F G R P

  3. (C)

    Node Q has only one child

  4. (D)

    The left subtree of node R contains the node G

Answer and solution
See the question in the paper
GATE 2026 DA Q.25: answer and solution

GATE 2025 CS1 Q.26

GATE 2025 · CS1Q.26 · 1 mark · MSQ

Which of the following statement(s) is/are TRUE for any binary search tree (BST) having distinct integers?

  1. (A)

    The maximum length of a path from the root node to any other node is .

  2. (B)

    An inorder traversal will always produce a sorted sequence of elements.

  3. (C)

    Finding an element takes time in the worst case.

  4. (D)

    Every BST is also a Min-Heap.

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.26: answer and solution

GATE 2025 CS2 Q.57

GATE 2025 · CS2Q.57 · 2 marks · NAT

In a B-tree where each node can hold at most four key values, a root to leaf path consists of the following nodes:

The *-marked keys signify that these are data entries in a leaf.

Assume that a pointer between keys and points to a subtree containing keys in , and that when a leaf is created, the smallest key in it is copied up into its parent.

A record with key value 23 is inserted into the B-tree.

The smallest key value in the parent of the leaf that contains 25* is ________. (Answer in integer)

Answer and solution
See the question in the paper
GATE 2025 CS2 Q.57: answer and solution

GATE 2024 CS2 Q.39

GATE 2024 · CS2Q.39 · 2 marks · MCQ

You are given a set of distinct integers. A binary search tree is created by inserting all elements of one by one, starting with an empty tree. The tree follows the convention that, at each node, all values stored in the left subtree of the node are smaller than the value stored at the node. You are not aware of the sequence in which these values were inserted into , and you do not have access to .

Which one of the following statements is TRUE?

  1. (A)

    Inorder traversal of can be determined from

  2. (B)

    Root node of can be determined from

  3. (C)

    Preorder traversal of can be determined from

  4. (D)

    Postorder traversal of can be determined from

Answer and solution
See the question in the paper
GATE 2024 CS2 Q.39: answer and solution

GATE 2023 CS Q.46

GATE 2023 · CSQ.46 · 2 marks · MCQ

Let be a priority queue for maintaining a set of elements. Suppose is implemented using a max-heap data structure. The operation extracts and deletes the maximum element from . The operation inserts a new element in . The properties of a max-heap are preserved at the end of each of these operations.

When contains elements, which one of the following statements about the worst case running time of these two operations is TRUE?

  1. (A)

    Both and run in .

  2. (B)

    Both and run in .

  3. (C)

    runs in whereas runs in .

  4. (D)

    runs in whereas runs in .

Answer and solution
See the question in the paper
GATE 2023 CS Q.46: answer and solution

GATE 2020 CS Q.41

GATE 2020 · CSQ.41 · 2 marks · MCQ

In a balanced binary search tree with elements, what is the worst case time complexity of reporting all elements in range ? Assume that the number of reported elements is .

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Official answer

Official answer: BSource: Official answer key, GATE 2020 CS (IIT Delhi)

See the question in the paper
GATE 2020 CS Q.41: official answer

PRACTICE

7 questions to test yourself

PRACTICE 11 mark · NAT

A full binary tree (every node has either 0 or exactly 2 children) has 12 leaf nodes. What is the total number of nodes in the tree?

Answer and solution

Answer:

  1. In any binary tree, , where is the number of leaves and the number of nodes with two children.

  2. With , this gives .

  3. The tree is full, so and the total is . This agrees with .

PRACTICE 22 marks · MCQ

A binary tree with distinct node labels has inorder traversal D B E A F C G and preorder traversal A B D E C F G. What is its postorder traversal?

  1. (A)

    D E B F G C A

  2. (B)

    D E B G F C A

  3. (C)

    B D E C F G A

  4. (D)

    A B D E C F G

Answer and solution

Answer: (A)

  1. The first element of the preorder is the root: A.

  2. Find A in the inorder: D B E | A | F C G. The left subtree's inorder is D B E and the right subtree's is F C G, 3 nodes each.

  3. The next 3 preorder elements belong to the left subtree and the last 3 to the right: left preorder B D E, right preorder C F G.

  4. Left subtree: the root is B, and the inorder D | B | E gives B the left child D and the right child E.

  5. Right subtree: the root is C, and the inorder F | C | G gives C the left child F and the right child G.

  6. Postorder (left, right, root): D, E, B, then F, G, C, then A.

  7. The postorder is D E B F G C A.

PRACTICE 32 marks · NAT

What is the minimum possible number of nodes in an AVL tree of height 4? (Height of a single-node tree is 0; height of an empty tree is -1.)

Answer and solution

Answer:

  1. Let be the minimum number of nodes in an AVL tree of height . The sparsest such tree is a root whose subtrees are sparsest AVL trees of heights and , so , with and .

  2. .

  3. .

  4. .

  5. . Check with : .

PRACTICE 42 marks · MSQ

Each array below is claimed to be a max-heap stored in the 1-indexed layout (index 1 is the root; the node at index has children at and and parent at ). Which of the arrays are valid max-heaps?

  1. (A)

    [50, 30, 40, 10, 20, 35]

  2. (B)

    [50, 40, 30, 20, 45, 25]

  3. (C)

    [45, 40, 42, 10, 15]

  4. (D)

    [50, 45, 40, 46, 20, 30]

Answer and solution

Answer: (A), (C)

  1. An array always forms a complete tree, so it is a max-heap exactly when every parent is each of its children.

  2. A = [50, 30, 40, 10, 20, 35]: 50 ≥ 30 and 50 ≥ 40 (indices 2, 3); 30 ≥ 10 and 30 ≥ 20 (indices 4, 5); 40 ≥ 35 (index 6). Valid.

  3. B = [50, 40, 30, 20, 45, 25]: the parent of index 5 is index 2, and 40 < 45. Invalid.

  4. C = [45, 40, 42, 10, 15]: 45 ≥ 40 and 45 ≥ 42; 40 ≥ 10 and 40 ≥ 15. Valid.

  5. D = [50, 45, 40, 46, 20, 30]: the parent of index 4 is index 2, and 45 < 46. Invalid.

  6. The valid max-heaps are A and C.

PRACTICE 51 mark · MCQ

How many distinct binary search trees can be formed on 4 distinct keys? (Two BSTs count as the same if they have the same shape and the same key at every position.)

  1. (A)

    14

  2. (B)

    16

  3. (C)

    24

  4. (D)

    42

Answer and solution

Answer: (A)

  1. A BST on distinct keys is fixed by its shape, because the inorder order puts the sorted keys into the positions. So the count is the number of binary tree shapes with nodes, the Catalan number .

  2. .

  3. Check with the recurrence: .

PRACTICE 62 marks · MCQ

The preorder traversal of a binary search tree with distinct integer keys is 40 25 10 30 28 60 50 70. What is its postorder traversal?

  1. (A)

    10 28 30 25 50 70 60 40

  2. (B)

    10 30 28 25 50 70 60 40

  3. (C)

    28 10 30 25 50 70 60 40

  4. (D)

    10 28 25 30 50 70 60 40

Answer and solution

Answer: (A)

  1. The first element is the root: 40. The keys smaller than 40 (25, 10, 30, 28) form the left subtree, in that preorder order. The keys larger than 40 (60, 50, 70) form the right subtree.

  2. Left subtree, preorder 25 10 30 28: the root is 25; 10 < 25 is its left subtree; 30 and 28 are its right subtree, where 30 is the root and 28 is 30's left child.

  3. Right subtree, preorder 60 50 70: the root is 60, with left child 50 and right child 70.

  4. Postorder of the left subtree: 10, then (28, 30), then 25, giving 10 28 30 25.

  5. Postorder of the right subtree: 50 70 60. Then the root, 40.

  6. The postorder is 10 28 30 25 50 70 60 40.

PRACTICE 71 mark · NAT

A max-heap holds 100 distinct keys in the 1-indexed array layout (index 1 is the root; the node at index has children at and ). Over all valid max-heaps on these keys, at how many different array indices can the smallest key appear?

Answer and solution

Answer:

  1. An internal node has at least one child, and in a max-heap with distinct keys that child is smaller than it. So the smallest key cannot be at an internal node: it must be at a leaf.

  2. In a 100-element heap, the node at index has a child exactly when , that is when . The leaves are indices 51 to 100: 50 positions.

  3. Every leaf is possible. Put the keys in decreasing order at indices 1 to 100, then swap the smallest key (at index 100) with the key at the chosen leaf . The leaf now holds the minimum, which is below its parent. Index 100 now holds the key of rank , and its parent, index 50 < , holds a larger key. Every other parent-child pair is unchanged, so the result is still a max-heap.

  4. So the smallest key can appear at exactly 50 indices.

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE CS

trees, binary search trees, binary heaps

GATE DA

trees

Preparing in Kolkata? IAE Academy's course for GATE CSE or GATE DA.