By the end of this chapter you'll be able to…

  • 1State and check the height convention before answering a counting question
  • 2Relate node count to edge count in any tree
  • 3Compute maximum and minimum nodes for a binary tree of given height
  • 4Compute the minimum height for a given number of nodes
  • 5Apply the leaf-versus-internal-node identity for strictly binary trees
  • 6Derive that identity from an edge-counting argument
  • 7Count distinct binary trees using the Catalan number
  • 8Distinguish preorder, inorder and postorder by visit placement
  • 9Match each traversal to its characteristic use
  • 10Explain why level-order uses a queue while the others use a stack
  • 11Reconstruct a tree from inorder with preorder or postorder
  • 12Explain why preorder with postorder is ambiguous and when it is not
  • 13State the binary search tree invariant precisely
  • 14Explain why operations cost the height and what the worst case is
  • 15Identify the insertion order that degenerates a BST
  • 16Handle all three cases of BST deletion
  • 17Locate the inorder predecessor and successor of a node
  • 18State the AVL balance condition
  • 19Identify LL, RR, LR and RL cases and apply the correct rotation
  • 20Explain why insertion needs one rotation and deletion may need many
  • 21Apply the minimum-node recurrence for AVL trees
  • 22Explain why B-trees widen nodes and why B+ trees link the leaves
  • 23Compare AVL and red-black trees by height and rotation count
💡
Why this chapter matters in GATE
Trees are where data structures stop being linear, and the payoff is immediate: a structure of n nodes can be searched in logarithmic rather than linear time, provided its height stays logarithmic. That proviso is the entire subject, because a binary search tree gives operations costing the height, and the height ranges from log n to n-1 depending on the insertion order. Everything from AVL trees to B-trees exists to force the height near its minimum. Almost every tree question is one of two things: a counting argument relating nodes to height, or a traversal that visits in a specific order. The counting arguments all come from one observation, that level i holds at most 2 to the i nodes. The traversals all come from another, that a recursive traversal visits a node before, between or after its two recursive calls, and those three placements are the only difference between preorder, inorder and postorder.

Before you start — revise these

🔗
Arrays, Stacks, Queues & Linked Lists
Depth-first traversals use a stack and level-order uses a queue, so the linear structures are the machinery every traversal is built from.
🔗
Programming in C & Recursion
The three depth-first traversals differ only in where the visit sits relative to the recursive calls, which is the order-of-work rule developed there.
🔗
Discrete Mathematics
Catalan numbers, the counting of tree shapes and the recurrence for minimum AVL nodes all use the combinatorics from that chapter.

Trees & Binary Search Trees

Trees are where data structures stop being linear, and the payoff is immediate: a structure of nodes can be searched in time instead of , provided its height stays logarithmic.

That proviso is the entire subject. A binary search tree gives operations where is the height, and can be anywhere from to depending on the insertion order. Everything from AVL trees to B-trees exists to force to stay near its minimum.

Almost every tree question is one of two things. Either a counting argument relating the number of nodes to the height, or a traversal that visits nodes in a specific order.

The counting arguments all come from the same observation: level of a binary tree holds at most nodes, so a tree of height holds at most .

The traversals all come from one observation too: a recursive traversal visits a node either before, between or after its two recursive calls, and those three placements are the only difference between preorder, inorder and postorder.

A convention must be fixed and stated, because both appear. Throughout this chapter, height is measured in edges, so a single node has height 0 and an empty tree has height . Some sources count nodes instead, giving answers one larger.

1. Counting Nodes and Heights

A tree with nodes has exactly edges, because every node except the root has exactly one parent edge.

For a binary tree of height measured in edges:

The maximum is achieved by a perfect tree with every level full; the minimum by a degenerate tree that is effectively a linked list.

Inverting the maximum gives the minimum possible height for nodes:

A strictly binary tree — one where every node has 0 or 2 children — satisfies a useful identity. If it has internal nodes then it has exactly leaves, so its total node count is always odd.

The identity generalises. In any binary tree, the number of nodes with two children is exactly one less than the number of leaves.

The number of structurally distinct binary trees with nodes is the -th Catalan number:

giving 1, 1, 2, 5, 14, 42 for through 5. The same count applies to binary search trees on distinct keys, because the shape determines the tree once the keys are fixed.

2. Traversals

Three depth-first traversals differ only in where the node's own visit sits relative to its two recursive calls.

TraversalOrder
PreorderNode, left subtree, right subtree
InorderLeft subtree, node, right subtree
PostorderLeft subtree, right subtree, node

Each has a characteristic use. Preorder produces a prefix expression and is the order in which a tree is copied or serialised, since a node is emitted before its children. Postorder produces a postfix expression and is the order in which a tree is deleted, since children are freed before their parent.

Inorder is the important one for search trees: applied to a binary search tree it visits the keys in sorted order, and this single fact underlies most BST questions.

Level-order traversal visits nodes level by level and is not recursive. It uses a queue: enqueue the root, then repeatedly dequeue a node, visit it, and enqueue its children.

The contrast is worth stating: depth-first traversals use a stack, explicitly or through recursion, while level-order uses a queue. That is the only structural difference between them, exactly as with graph search.

3. Reconstruction from Traversals

Given two traversals, can the tree be recovered uniquely? The answer depends on which two.

Inorder plus preorder determines the tree uniquely. The first element of the preorder is the root; locating it in the inorder splits the remaining keys into the left and right subtrees; recurse on each part.

Inorder plus postorder also determines it uniquely, using the last postorder element as the root instead.

Preorder plus postorder does not. Without inorder there is no way to tell which subtree is which when a node has only one child, so any node with a single child could have it on either side.

The exception is worth knowing: for a strictly binary tree, preorder plus postorder does determine the tree, because no node has exactly one child and the ambiguity cannot arise.

Inorder alone determines nothing, since every binary search tree on the same key set has the same inorder traversal — the sorted sequence.

4. Binary Search Trees

A binary search tree maintains the invariant that every key in a node's left subtree is smaller than the node's key, and every key in the right subtree is larger.

The invariant is about entire subtrees, not just immediate children, and questions are built by presenting a tree that satisfies the weaker child-only condition and asking whether it is a valid BST.

Search descends from the root, going left or right by comparison, and stops on a match or a null pointer. Every operation costs , and since ranges from to , the same operation can be logarithmic or linear.

Inserting keys in sorted order produces the worst case: each new key is larger than everything present, so it becomes the right child of the previous one and the tree degenerates into a list.

Deletion has three cases, and the third is the one examined.

A leaf is removed directly. A node with one child is replaced by that child. A node with two children is replaced by its inorder predecessor or successor, whose value is copied into the node, and that predecessor or successor is then deleted — a case that has at most one child, so the recursion terminates.

The inorder successor of a node with a right subtree is the leftmost node of that subtree, and the inorder predecessor is the rightmost node of the left subtree.

5. AVL Trees

An AVL tree keeps the height logarithmic by enforcing a local balance condition.

The balance factor of a node is the height of its left subtree minus the height of its right subtree, and it must be , or .

Insertion or deletion can violate this at some node, and the violation is repaired by a rotation. Four cases exist, named by the direction of the two steps from the unbalanced node down to the newly inserted node.

CaseInsertion pathFix
LLLeft, then leftSingle right rotation
RRRight, then rightSingle left rotation
LRLeft, then rightLeft rotation, then right
RLRight, then leftRight rotation, then left

A single rotation fixes the outer cases; the inner cases need two. The reason is that an inner insertion moves the node that must become the new root into a grandchild position, and one rotation cannot promote it far enough.

Rebalancing after an insertion requires at most one rotation — single or double — because the rotation restores the subtree's original height and no ancestor's balance changes. Deletion may require rotations all the way to the root, because a rotation can shorten a subtree and propagate the imbalance upward.

The minimum number of nodes in an AVL tree of height satisfies a Fibonacci-like recurrence:

with and . Because this grows exponentially, the height of an AVL tree with nodes is — approximately in the worst case.

6. Multiway Search Trees

When the data lives on disk rather than in memory, the cost model changes: a disk access costs vastly more than a comparison, so the goal becomes minimising the number of nodes visited rather than the number of comparisons.

A B-tree of order stores up to keys and children per node, and every leaf sits at the same depth. Making a node the size of a disk block means one disk read brings in many keys, and the height falls to roughly .

A B+ tree stores all data in the leaves and uses internal nodes only as an index, with the leaves linked together. This makes a range scan a single traversal of the linked leaves rather than a repeated descent, which is why database indexes use B+ trees rather than B-trees.

A red-black tree is an alternative balanced binary tree with a weaker balance condition than AVL. It permits a taller tree — up to — but performs fewer rotations on modification, which makes it preferable when updates are frequent and AVL preferable when lookups dominate.

7. Worked Examples

Example 1. A binary tree has 20 leaves and every internal node has exactly two children. How many nodes does it have in total?

For a strictly binary tree, the number of leaves is one more than the number of internal nodes.

So gives , and .

The total is nodes.

The identity is worth deriving rather than memorising. Each internal node contributes 2 edges, so there are edges. Every node except the root has exactly one parent edge, so there are edges. Equating: , which gives .

Example 2. The preorder traversal of a binary tree is A B D E C F and the inorder is D B E A C F. Reconstruct the tree and give its postorder.

The first preorder element is the root, so A is the root.

Locate A in the inorder: D B E | A | C F. Everything to the left, D B E, forms the left subtree; everything to the right, C F, forms the right subtree.

The preorder after A is B D E C F, so the next 3 elements B D E describe the left subtree and the remaining C F the right.

For the left subtree, preorder B D E and inorder D B E. Root is B, with D on the left and E on the right — both leaves.

For the right subtree, preorder C F and inorder C F. Root is C. In the inorder, nothing precedes C, so its left subtree is empty and F is its right child.

The tree has root A, left child B with children D and E, and right child C with right child F.

Postorder visits left, right, then node: D E B F C A.

Note that the right subtree here has a node with a single child, which is exactly the configuration that would make preorder-plus-postorder ambiguous. Inorder is what resolved it.

Example 3. Insert 50, 30, 70, 20, 40, 60, 80 into an empty BST, then delete 30. Show the result.

Insertion places each key by descending from the root.

50 becomes the root. 30 is smaller, so it goes left. 70 is larger, so it goes right. 20 is smaller than 50 and than 30, so it becomes 30's left child. 40 is smaller than 50 but larger than 30, so it becomes 30's right child. 60 is larger than 50 and smaller than 70, so it becomes 70's left child. 80 becomes 70's right child.

The tree is perfectly balanced with height 2.

Now delete 30. It has two children, 20 and 40, so it is the third deletion case.

Replace it by its inorder predecessor, the rightmost node of its left subtree, which is 20. Copy 20 into the node and delete the original 20, which is a leaf.

The result has root 50, left child 20 with right child 40, and right child 70 with children 60 and 80.

Using the inorder successor instead would have given 40 in that position with 20 as its left child, which is equally valid — either choice preserves the invariant, and a question must say which is intended.

Example 4. What is the minimum number of nodes in an AVL tree of height 5?

Use the recurrence , which says that a minimal tree of height has a root plus minimal subtrees of heights and — the most unbalanced arrangement the AVL condition permits.

, a single node. , a root with one child. . . . .

The minimum is 20 nodes.

The sequence 1, 2, 4, 7, 12, 20 is each Fibonacci number minus one, which is why the growth is exponential and the height stays logarithmic. For comparison, an unbalanced binary tree of height 5 needs only 6 nodes.

Example 5. Inserting 10, 20, 30 into an empty AVL tree causes an imbalance. Identify the case and perform the rotation.

Insert 10: it becomes the root, balance factor 0.

Insert 20: larger, so it becomes the right child. The root's balance factor is , which is permitted.

Insert 30: larger than both, so it becomes 20's right child. Now the root has an empty left subtree of height and a right subtree of height 1, giving a balance factor of . The condition is violated at the root.

Trace the path from the unbalanced node to the new node: right, then right. This is the RR case, fixed by a single left rotation about the unbalanced node.

The rotation makes 20 the new root, with 10 as its left child and 30 as its right child.

Every balance factor is now 0 and the height has fallen from 2 to 1.

Had the insertions been 10, 30, 20 instead, the path would have been right then left — the RL case — requiring a right rotation about 30 followed by a left rotation about 10, and arriving at the same final tree.

Example 6. How many structurally distinct binary search trees can be built from the keys 1, 2, 3, 4?

The number of distinct binary tree shapes on nodes is the -th Catalan number, and for a BST the shape determines the tree completely, since the key placement is forced by the ordering invariant.

There are 14 distinct binary search trees.

The recursive derivation is worth seeing. Choosing key as the root forces the smaller keys into the left subtree and the larger keys into the right, so the count is the sum over of .

That is , confirming the closed form.

Note the contrast with plain binary trees on 4 labelled nodes, where the labels can be permuted and the count is . The BST invariant removes that freedom entirely.

Summary

Height is measured in edges here: a single node has height 0. Sources counting nodes give answers one larger, so the convention must be checked.

A tree with nodes has edges. A binary tree of height holds between and nodes, so the minimum height for nodes is .

A strictly binary tree has one more leaf than internal nodes. The number of distinct binary trees on nodes is the Catalan number.

Preorder, inorder and postorder differ only in where the node's visit sits relative to the two recursive calls. Level-order uses a queue where the others use a stack.

Inorder traversal of a BST gives sorted order, which is the fact most BST questions rest on.

Inorder with either preorder or postorder reconstructs a tree uniquely; preorder with postorder does not, except for strictly binary trees.

The BST invariant constrains entire subtrees, not just immediate children. Operations cost , and sorted insertion produces the degenerate linear case.

Deleting a two-child node replaces it with the inorder predecessor or successor, which has at most one child.

An AVL tree keeps every balance factor in . Outer imbalances need one rotation and inner ones need two. Insertion needs at most one rotation; deletion may need rotations up to the root.

The minimum AVL node count follows a Fibonacci-like recurrence, which forces the height to .

B-trees and B+ trees trade comparisons for disk accesses by widening nodes, and B+ trees additionally link the leaves so that range scans need no re-descent.

Key formulas & results

Everything to memorise for the exam hall, in one card. Screenshot this for revision.

The organising tool
ALMOST EVERY TREE QUESTION IS EITHER A COUNTING ARGUMENT RELATING NODES TO HEIGHT, OR A TRAVERSAL THAT VISITS IN A SPECIFIC ORDER.
ALL COUNTING COMES FROM LEVEL i HOLDING AT MOST 2^i NODES. ALL TRAVERSALS COME FROM WHERE THE VISIT SITS RELATIVE TO THE TWO RECURSIVE CALLS.
The height convention
HEIGHT IS MEASURED IN EDGES HERE: A SINGLE NODE HAS HEIGHT 0 AND AN EMPTY TREE HAS HEIGHT MINUS 1.
SOURCES THAT COUNT NODES GIVE ANSWERS ONE LARGER. THE CONVENTION MUST BE CHECKED BEFORE ANY COUNTING QUESTION IS ATTEMPTED.
Nodes and edges
A TREE WITH n NODES HAS EXACTLY n MINUS 1 EDGES.
EVERY NODE EXCEPT THE ROOT HAS EXACTLY ONE PARENT EDGE, WHICH IS THE WHOLE PROOF AND ALSO THE BASIS OF SEVERAL OTHER IDENTITIES.
Node bounds for a height
A BINARY TREE OF HEIGHT h HOLDS AT MOST 2^(h+1) MINUS 1 NODES AND AT LEAST h PLUS 1.
THE MAXIMUM IS A PERFECT TREE WITH EVERY LEVEL FULL; THE MINIMUM IS A DEGENERATE TREE THAT IS EFFECTIVELY A LINKED LIST.
Minimum height
THIS IS THE INVERSE OF THE MAXIMUM-NODE FORMULA, AND IT IS THE BOUND EVERY BALANCED TREE IS TRYING TO STAY NEAR.
Strictly binary trees
IF EVERY NODE HAS 0 OR 2 CHILDREN, THEN LEAVES EQUAL INTERNAL NODES PLUS ONE, SO THE TOTAL NODE COUNT IS ALWAYS ODD.
DERIVE IT BY EDGE COUNTING: EACH INTERNAL NODE CONTRIBUTES 2 EDGES, AND THE TOTAL EDGES ARE n MINUS 1, SO 2I EQUALS I PLUS L MINUS 1.
Two-child nodes and leaves
IN ANY BINARY TREE, THE NUMBER OF NODES WITH TWO CHILDREN IS EXACTLY ONE LESS THAN THE NUMBER OF LEAVES.
THIS GENERALISES THE STRICTLY-BINARY IDENTITY AND HOLDS EVEN WHEN SOME NODES HAVE A SINGLE CHILD.
Catalan number
THE NUMBER OF STRUCTURALLY DISTINCT BINARY TREES ON n NODES IS C_n = (1/(n+1)) TIMES C(2n, n), GIVING 1, 1, 2, 5, 14, 42.
THE SAME COUNT APPLIES TO BINARY SEARCH TREES ON n DISTINCT KEYS, BECAUSE THE ORDERING INVARIANT FIXES THE KEYS ONCE THE SHAPE IS CHOSEN.
The three depth-first traversals
PREORDER IS NODE, LEFT, RIGHT. INORDER IS LEFT, NODE, RIGHT. POSTORDER IS LEFT, RIGHT, NODE.
PREORDER SERIALISES A TREE AND GIVES PREFIX EXPRESSIONS; POSTORDER DELETES A TREE AND GIVES POSTFIX; INORDER ON A BST GIVES SORTED ORDER.
Level-order
LEVEL-ORDER VISITS LEVEL BY LEVEL USING A QUEUE: ENQUEUE THE ROOT, THEN REPEATEDLY DEQUEUE, VISIT, AND ENQUEUE THE CHILDREN.
DEPTH-FIRST TRAVERSALS USE A STACK AND LEVEL-ORDER USES A QUEUE, WHICH IS THE ONLY STRUCTURAL DIFFERENCE BETWEEN THEM.
Reconstruction
INORDER PLUS PREORDER DETERMINES A TREE UNIQUELY, AS DOES INORDER PLUS POSTORDER. PREORDER PLUS POSTORDER DOES NOT.
WITHOUT INORDER THERE IS NO WAY TO TELL WHICH SIDE A SINGLE CHILD SITS ON. FOR A STRICTLY BINARY TREE THAT CASE CANNOT ARISE, SO THE PAIR SUFFICES.
Inorder alone
INORDER ALONE DETERMINES NOTHING, SINCE EVERY BST ON THE SAME KEY SET HAS THE SAME INORDER TRAVERSAL.
THAT SEQUENCE IS ALWAYS THE SORTED ORDER, WHICH IS WHY IT CARRIES NO SHAPE INFORMATION AT ALL.
The BST invariant
EVERY KEY IN A NODE'S LEFT SUBTREE IS SMALLER THAN THE NODE'S KEY AND EVERY KEY IN ITS RIGHT SUBTREE IS LARGER.
THE CONSTRAINT IS ON ENTIRE SUBTREES, NOT JUST IMMEDIATE CHILDREN, AND QUESTIONS ARE BUILT BY PRESENTING A TREE SATISFYING ONLY THE WEAKER CONDITION.
BST operation cost
SEARCH, INSERT AND DELETE ALL COST O(h), AND h RANGES FROM log2 n TO n MINUS 1.
INSERTING KEYS IN SORTED ORDER PRODUCES THE WORST CASE, BECAUSE EACH NEW KEY BECOMES THE RIGHT CHILD OF THE PREVIOUS ONE.
BST deletion cases
A LEAF IS REMOVED DIRECTLY. A ONE-CHILD NODE IS REPLACED BY THAT CHILD. A TWO-CHILD NODE IS REPLACED BY ITS INORDER PREDECESSOR OR SUCCESSOR, WHICH IS THEN DELETED.
THE REPLACEMENT HAS AT MOST ONE CHILD, SO THE RECURSION TERMINATES. EITHER PREDECESSOR OR SUCCESSOR IS VALID, SO A QUESTION MUST SAY WHICH IS INTENDED.
Predecessor and successor
THE INORDER SUCCESSOR OF A NODE WITH A RIGHT SUBTREE IS THE LEFTMOST NODE OF THAT SUBTREE; THE PREDECESSOR IS THE RIGHTMOST NODE OF THE LEFT SUBTREE.
BOTH ARE REACHED BY ONE STEP SIDEWAYS AND THEN AS FAR AS POSSIBLE IN THE OPPOSITE DIRECTION.
AVL balance condition
THE BALANCE FACTOR IS LEFT SUBTREE HEIGHT MINUS RIGHT SUBTREE HEIGHT, AND IT MUST BE MINUS 1, 0 OR PLUS 1 AT EVERY NODE.
A VIOLATION IS REPAIRED BY A ROTATION, AND THE CASE IS NAMED BY THE DIRECTION OF THE TWO STEPS FROM THE UNBALANCED NODE TOWARD THE NEW NODE.
The four rotation cases
LL NEEDS A SINGLE RIGHT ROTATION. RR NEEDS A SINGLE LEFT ROTATION. LR NEEDS A LEFT THEN A RIGHT. RL NEEDS A RIGHT THEN A LEFT.
OUTER CASES NEED ONE ROTATION AND INNER CASES NEED TWO, BECAUSE AN INNER INSERTION PUTS THE FUTURE ROOT IN A GRANDCHILD POSITION.
Rotations after insertion versus deletion
INSERTION NEEDS AT MOST ONE ROTATION, SINGLE OR DOUBLE. DELETION MAY NEED ROTATIONS ALL THE WAY TO THE ROOT.
AN INSERTION ROTATION RESTORES THE SUBTREE'S ORIGINAL HEIGHT SO NO ANCESTOR CHANGES, WHILE A DELETION ROTATION CAN SHORTEN A SUBTREE AND PROPAGATE UPWARD.
Minimum AVL nodes
N(h) = N(h-1) + N(h-2) + 1 WITH N(0) = 1 AND N(1) = 2, GIVING 1, 2, 4, 7, 12, 20.
THE SEQUENCE IS EACH FIBONACCI NUMBER MINUS ONE, SO IT GROWS EXPONENTIALLY AND THE AVL HEIGHT IS ABOUT 1.44 log2 n IN THE WORST CASE.
B-trees and B+ trees
A B-TREE OF ORDER m STORES UP TO m MINUS 1 KEYS AND m CHILDREN PER NODE WITH ALL LEAVES AT THE SAME DEPTH, GIVING HEIGHT ABOUT log base m OF n.
A B+ TREE KEEPS ALL DATA IN LINKED LEAVES AND USES INTERNAL NODES ONLY AS AN INDEX, WHICH MAKES A RANGE SCAN ONE TRAVERSAL RATHER THAN REPEATED DESCENTS.
AVL versus red-black
A RED-BLACK TREE PERMITS A TALLER TREE, UP TO 2 log2(n PLUS 1), BUT PERFORMS FEWER ROTATIONS ON MODIFICATION.
RED-BLACK IS PREFERABLE WHEN UPDATES ARE FREQUENT AND AVL WHEN LOOKUPS DOMINATE, WHICH IS WHY LIBRARY MAPS USUALLY CHOOSE RED-BLACK.
⚠️

Traps GATE sets — and how to dodge them

These are the exact option-traps and misreads that cost marks under negative marking.

WATCH OUT
Using the wrong height convention
Measuring in edges gives a single node height 0; measuring in nodes gives height 1. Every node-count formula shifts by one between the two, so the convention must be established from the question before computing.
WATCH OUT
Checking the BST invariant against immediate children only
The constraint covers entire subtrees. A node whose left child is smaller but whose left grandchild exceeds the node itself violates the invariant, and questions are built precisely around that configuration.
WATCH OUT
Assuming BST operations are logarithmic
They cost the height, which is logarithmic only if the tree is balanced. Inserting sorted keys produces a degenerate tree of height n minus 1, making every operation linear.
WATCH OUT
Reconstructing a tree from preorder and postorder
The pair is ambiguous whenever a node has exactly one child, since nothing indicates which side it is on. Inorder is what resolves it, and only for strictly binary trees does the ambiguity disappear.
WATCH OUT
Expecting inorder alone to identify a BST
Every BST on the same keys has the identical sorted inorder traversal, so it carries no shape information. A second traversal is always required.
WATCH OUT
Deleting a two-child node by promoting an arbitrary child
That breaks the ordering invariant. The replacement must be the inorder predecessor or successor, which is the only value that preserves the ordering with respect to both subtrees.
WATCH OUT
Confusing the LR case with the LL case
The case is named by the direction of both steps from the unbalanced node to the new node. Left then left is LL and needs one rotation; left then right is LR and needs two, because the new root sits in a grandchild position.
WATCH OUT
Assuming AVL deletion needs at most one rotation
That holds for insertion, where the rotation restores the original subtree height. A deletion rotation can shorten a subtree, so the imbalance can propagate and rotations may be needed at every level up to the root.
WATCH OUT
Applying the AVL minimum-node recurrence without the plus one
The recurrence is N(h-1) plus N(h-2) plus 1, where the extra term is the root itself. Omitting it gives the Fibonacci numbers rather than the correct sequence 1, 2, 4, 7, 12, 20.
WATCH OUT
Counting labelled trees when the question asks for BSTs
For a BST the keys are forced by the shape, so the count is the Catalan number alone. Labelled binary trees additionally permute the keys and give the Catalan number times n factorial.
WATCH OUT
Implementing level-order with a stack
A stack produces a depth-first order. Level-order requires a queue, because nodes must be visited in the order they were discovered rather than in reverse.
WATCH OUT
Assuming a B-tree and a B+ tree are interchangeable
A B-tree stores data throughout, so a range scan must re-descend for each key. A B+ tree keeps all data in linked leaves, making a range scan one sequential walk, which is why database indexes use it.

Exam-pattern practice

PYQ-style questions with full solutions. Work through them as a readiness check — mark yourself honestly and get your gap report at the end.

Readiness check

Are you exam-ready for Trees & Binary Search Trees?

9 problems from this chapter. Try each one, reveal the worked solution, mark yourself honestly — get your gap report at the end.

9 questions~6 min

5-minute revision

The whole chapter, distilled. Read this the night before the exam.

  • Check the height convention before any counting question.
  • A tree with n nodes has n minus 1 edges.
  • Level i holds at most 2 to the i nodes.
  • Maximum nodes at height h is 2^(h+1) minus 1.
  • Minimum nodes at height h is h plus 1.
  • Minimum height for n nodes is ceil(log2(n+1)) minus 1.
  • A strictly binary tree has leaves equal to internal nodes plus one.
  • Its total node count is always odd.
  • Two-child nodes number one fewer than leaves.
  • Distinct binary trees on n nodes is the Catalan number.
  • Preorder is node, left, right.
  • Inorder is left, node, right.
  • Postorder is left, right, node.
  • Preorder serialises; postorder deletes.
  • Inorder on a BST gives sorted order.
  • Level-order uses a queue.
  • Inorder plus preorder reconstructs uniquely.
  • Inorder plus postorder reconstructs uniquely.
  • Preorder plus postorder is ambiguous.
  • It suffices for strictly binary trees only.
  • Inorder alone determines nothing.
  • The BST invariant covers entire subtrees.
  • BST operations cost the height.
  • Sorted insertion degenerates a BST to a list.
  • A leaf deletes directly.
  • A one-child node is replaced by its child.
  • A two-child node is replaced by predecessor or successor.
  • The successor is the leftmost node of the right subtree.
  • AVL balance factors must be minus 1, 0 or plus 1.
  • LL and RR need one rotation.
  • LR and RL need two.
  • Insertion needs at most one rotation.
  • Deletion may need rotations up to the root.
  • Minimum AVL nodes follow N(h-1) + N(h-2) + 1.
  • AVL height is about 1.44 log2 n.
  • B-trees widen nodes to cut disk accesses.
  • B+ trees link leaves for range scans.
  • Red-black trees are taller but rotate less.

GATE question blueprint

How this topic is asked, tier by tier — so you can prep to the pattern.

Typical weightage: Programming & Data Structures contributes roughly 8-10 of the 72 core-CS marks; trees supply 3-4 of those across 2-3 questions

Question styleMarks eachTypical countWhat it tests
Node counting1~1Height bounds, edge counts and the height convention
Strictly binary trees1~1The leaf-versus-internal identity and its derivation
Traversals1~1Visit placement, characteristic uses and the queue-versus-stack contrast
Reconstruction2~1Which traversal pairs determine a tree and why preorder with postorder does not
BST operations2~1Insertion order, the three deletion cases and predecessor or successor choice
AVL trees2~1Minimum-node recurrence and maximum height for a node count
AVL rotations2~1Identifying the case and applying single or double rotations
Counting trees2~1Catalan numbers and the distinction between BSTs and labelled trees

Exam-hall strategy

Battle-tested tips from mentors and toppers for this topic under the sectional clock.

  1. Establish the height convention before doing any counting.
  2. For reconstruction, use inorder to find the subtree boundary and recurse.
  3. For BST questions, verify the result by checking that the inorder is sorted.
  4. For AVL height bounds, use the minimum-node recurrence rather than guessing.
  5. Name a rotation case by the direction of both steps toward the new node.
  6. For counting BSTs use the Catalan number alone; multiply by n factorial only for labelled trees.
  7. Node counts, heights and rotation counts are commonly set as NAT, which carries no negative marking, so never leave one blank.
  8. For 1-mark and 2-mark MCQs, negative marking is -1/3 and -2/3, so guess only after eliminating an option.
  9. GATE gives a single freely-navigable 180-minute window, so flag a long insertion trace and return to it.

Beyond the exam

Where this skill shows up in the job you're competing for — and in life.

An in-memory ordered map

Standard library map types are balanced binary search trees, and the choice of red-black over AVL reflects a preference for fewer rotations on update.

A database index

B+ trees are used because a range scan walks the linked leaves once instead of re-descending, and because wide nodes cut the number of disk accesses.

Expression trees in a compiler

Postorder traversal of an expression tree emits exactly the postfix form a stack machine executes, which is why the two topics keep meeting.

Serialising a hierarchy

Preorder emits a parent before its children, which is precisely what a file format or a copy operation needs in order to rebuild the structure as it reads.

Where else this topic is tested

Prepare once, score in every exam that asks it.

GATE DAModerate overlap — trees and traversals appear, with less emphasis on AVL rotation detail
UGC NET Computer ScienceHigh overlap — traversals, BST operations and AVL balance conditions are examined as direct recall
ISRO / BARC / DRDO computer science papersVery high overlap — node counting, reconstruction from traversals and AVL minimum-node questions are recurring MCQ topics

Questions aspirants ask

Pulled from the Q&A community and mentor sessions.

Because every node-counting formula shifts by exactly one between the two conventions, and a question that assumes the other one turns a correct derivation into a wrong answer. Measuring height in edges, a single node has height 0, an empty tree has height minus 1, and a binary tree of height h holds at most 2 to the power h plus 1, minus 1 nodes. Measuring in nodes, a single node has height 1 and the same tree has height h plus 1, so the maximum node count becomes 2 to the power h, minus 1. Both are standard and both appear in textbooks and past papers. The practical discipline is to establish the convention from the question before writing anything. A question that says a single node has height 1, or that gives the height of a two-level tree as 2, is using the node convention. A question that says the height of a single node is 0 is using edges. If the question gives no clue, state the assumption explicitly in the answer and derive consistently, which protects the working even if the marking key used the other convention. The same care applies to depth and level, which are also sometimes counted from 0 and sometimes from 1, and to the definition of a full versus a complete versus a perfect tree, where terminology genuinely varies between sources.

Because inorder is the only traversal that records where the boundary between the two subtrees falls. Preorder places the root at the front of each segment and postorder places it at the back, so both identify the root immediately; what neither supplies is how many nodes belong to the left subtree. Inorder answers exactly that: locating the root within the inorder sequence splits the remaining keys into everything on its left and everything on its right, and the sizes of those two blocks determine how to split the other traversal. The recursion then proceeds on each half. Without inorder, the ambiguity is concrete and small. A root with a single child produces the same preorder and the same postorder whether that child is on the left or the right. Root A with left child B gives preorder A B and postorder B A; root A with right child B gives exactly the same two sequences. The trees differ and the traversals do not. For a strictly binary tree the ambiguity disappears, because no node has exactly one child. There the second element of the preorder must be the root of the left subtree, and finding it in the postorder locates the boundary, so preorder plus postorder is sufficient. This exception is worth remembering because questions test it directly, presenting a strictly binary tree and asking whether the pair determines it.

Because those are the only two values that preserve the ordering invariant with respect to both subtrees simultaneously. The node being deleted sits between everything in its left subtree and everything in its right subtree. Whatever replaces it must satisfy the same relation: greater than every key on the left and smaller than every key on the right. The inorder predecessor is the largest key in the left subtree, so it is greater than everything else on the left by definition and smaller than everything on the right because it came from the left subtree. The inorder successor is the smallest key in the right subtree and satisfies the mirror argument. No other key in the tree has this property. Promoting an arbitrary child, for example, breaks the invariant immediately, since a left child is smaller than many keys that would end up beneath it on the right. The second reason the choice is convenient is that the replacement always has at most one child. The predecessor is the rightmost node of the left subtree, so by construction it has no right child; the successor is the leftmost node of the right subtree, so it has no left child. Deleting it therefore falls into the first or second case rather than recursing into a third two-child deletion, and the procedure terminates after one extra step. Either choice is correct, so a question expecting a specific tree must state which convention it uses.

Because an insertion rotation restores the subtree to the height it had before the insertion, while a deletion rotation can leave the subtree shorter than it was. Consider insertion. Adding a node can increase a subtree's height by at most one, and the imbalance appears at the lowest ancestor whose balance factor reaches plus or minus two. Performing the appropriate single or double rotation at that node produces a subtree whose height equals what it was before the insertion, because the rotation redistributes the extra level rather than absorbing it. Every ancestor above therefore sees an unchanged subtree height, its balance factor is unaffected, and no further work is needed. One rotation suffices, always. Deletion behaves differently. Removing a node can decrease a subtree's height, and the rotation that rebalances the affected node may itself produce a subtree one level shorter than before. The parent now sees a shortened child, which can push its own balance factor to plus or minus two, requiring another rotation, and the effect can cascade all the way to the root. In the worst case the number of rotations is proportional to the height, so logarithmic in the node count. This asymmetry is examined directly and is worth stating precisely: at most one rotation per insertion, and up to order log n rotations per deletion. It is also one reason red-black trees are preferred where deletions are frequent, since their weaker balance condition bounds rotations by a constant in both directions.

When the data lives on disk rather than in memory, because the cost model changes completely. In memory, the dominant cost is the number of comparisons, and a binary tree of height log base 2 of n minimises it. On disk, a single access costs on the order of milliseconds while a comparison costs nanoseconds, so the dominant cost is the number of nodes visited and comparisons within a node are effectively free. A B-tree exploits this by making each node the size of a disk block, holding perhaps hundreds of keys. One disk read then brings in the whole node, and the height falls from log base 2 of n to log base m of n, where m is the branching factor. For a million records, a binary tree needs about twenty disk accesses and a B-tree of order 100 needs three. That difference is the entire justification. A B+ tree refines it further by storing all data in the leaves and using internal nodes purely as an index, with the leaves linked in sequence. Two benefits follow. Internal nodes hold only keys and pointers, so they pack more keys per block and the tree is shallower still. And a range query descends once to the first matching leaf and then walks the leaf links, rather than re-descending for every key in the range. That is why database indexes and file systems use B+ trees almost universally, while AVL and red-black trees remain the choice for in-memory ordered maps.
Header Logo