algoritmauzmanı
Sign in
TREN
6.7Exam Practice
Lesson 6.7.1

Trees: exam questions and answers

This page is the exam practice for the trees section. University exams ask about trees in a few recurring ways: reading the terms off a tree, node and height formulas, traversal outputs, index arithmetic in the array layout, tracing BST insertions and deletions, rebuilding a tree from its traversals, expression trees and writing short recursive functions. Here you get original questions of each kind with step-by-step answers.

What you will learn
  • How to read the terms, the node and height formulas and the array indexes off a tree quickly
  • How to write traversal outputs, trace BST insertions and deletions and rebuild a tree from its traversals
  • How to write short recursive functions such as counting leaves, mirroring and checking for a BST, and give their cost
30 min

1Terms and properties

The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams, homework and exercise sheets of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare. Drawing the tree on paper is the shortest way to avoid mistakes in traversal and BST questions. The names in the code match the lessons on the linked binary tree and the linked BST.

DGEBFCA
The tree for questions 1 and 6.
1For the tree above, give: the root, the leaves, the inner nodes, the parent of G, the children of B, the sibling of D, the depth of G, the height of the tree, and the degree of B and of C.Midterm · concept

All the terms are read off one tree. The is the node with no parent, a is a node with no children, and the rest are inner nodes.

QuestionAnswerWhy
RootAIt has no parent
LeavesD, G, FThey have no children
Inner nodesA, B, C, EThey have at least one child
Parent of GEG is directly below E
Children of BD, E
Sibling of DESame parent: B
Depth of G3A → B → E → G: 3 edges
Height of the tree3The deepest leaf is G
DegreeB: 2, C: 1Number of children

See What is a tree? Basic terms.

2What is the difference between a full, a perfect and a complete binary tree? Which kinds does each of the three trees below belong to?Midterm · concept

The three definitions test three different things. In a full tree every node has either 0 or 2 children. In a perfect tree every inner node has 2 children and all leaves are on the same level. In a complete tree every level except the last is full, and the last level fills from left to right with no gaps.

45231
Tree 1: 3 has no children, 2 has two.
452631
Tree 2: on the last level 4, 5, 6 from left to right.
4526731
Tree 3: every level is full.
TreeFullCompletePerfect
1YesYesNo
2No (3 has one child)YesNo
3YesYesYes

Turkish textbooks name these three kinds differently from book to book, so in a Turkish exam it helps to write the English name or the definition next to the word. See What is a binary tree?.

3How many nodes can a binary tree of height 4 have at most and at least? What is the smallest possible height of a binary tree with 100 nodes?Midterm · concept

Level k holds at most 2^k nodes. A tree of height h has levels 0 to h, so it has at most 1 + 2 + 4 + ... + 2^h = 2^(h+1) - 1 nodes. The fewest nodes come from a chain with one node per level: h + 1.

  • For h = 4: at most 2^5 - 1 = 31 and at least 4 + 1 = 5 nodes.
  • For 100 nodes: a tree of height 5 holds at most 63 nodes, not enough. A tree of height 6 holds at most 127. The smallest height is 6; the general formula is ⌊log₂ n⌋ = ⌊log₂ 100⌋ = 6.

See Number of nodes and height.

4A binary tree has 12 nodes with two children and 5 nodes with one child. How many leaves does it have? How many nodes and edges does it have in total?Final · concept

In every binary tree the number of leaves is one more than the number of nodes with two children: n₀ = n₂ + 1. You can see it by counting the edges two ways: every node except the root has one edge up to its parent, so there are n - 1 edges; counted from the parents, there are n₁ + 2n₂.

  1. n = n₀ + n₁ + n₂ and n - 1 = n₁ + 2n₂. Together they give n₀ = n₂ + 1.
  2. Leaves: n₀ = 12 + 1 = 13.
  3. Total nodes: 13 + 5 + 12 = 30. Edges: 30 - 1 = 29.

The number of one-child nodes does not change the number of leaves; it only adds to the total.

5In a binary tree of 20 nodes stored with linked nodes, how many left or right fields are NULL?Midterm · concept

The answer is 21. Each node has two pointer fields: 2 × 20 = 40 fields in all. Every node except the root is pointed to by exactly one field, so 19 fields are used. The remaining 40 - 19 = 21 fields are NULL. The general formula: a tree with n nodes has n + 1 NULL pointers.

This number shows the wasted space of linked nodes and is used in the array or linked nodes comparison.

6One textbook gives the height of the tree in question 1 as 3, another as 4. Which one is right? Which definition does the function below use?Final · code reading

Both are right; they use two different definitions. On this site height counts edges: a single node has height 0 and an empty tree -1. Some books define height as the number of levels (nodes): a single node has height 1 and an empty tree 0. In the tree of question 1 the longest path is A, B, E, G: 3 edges, 4 nodes.

int height(struct TreeNode* root) {    if (root == NULL) return 0;    int l = height(root->left);    int r = height(root->right);    return 1 + (l > r ? l : r);}

This function returns 0 for an empty tree, so it uses the levels definition and gives 4 for the tree in question 1. To switch to the edges definition, change the base case to return -1;. Writing which definition you use at the start of an exam answer saves points.

2Traversal outputs

HDEBIJFGCA
The tree for question 7.
7Write the preorder, inorder, postorder and level-order traversals of the tree above.Midterm · trace

Each traversal does the same recursion in a different order: is root, left, right; is left, root, right; is left, right, root. reads row by row, left to right.

TraversalOutput
PreorderA B D H E C F I J G
InorderD H B E A I F J C G
PostorderH D E B I J F G C A
Level orderA B C D E F G H I J

The tricky node is H: it is the right child of D. In inorder, D comes before H (first D's empty left subtree, then D, then H). A quick check: preorder starts with the root and postorder ends with it.

See Preorder, Inorder, Postorder, Level order.

8The values 50, 30, 70, 20, 40, 60, 80, 35, 45, 65 are inserted in this order into an empty binary search tree. Draw the tree and give its height and its three traversals.Midterm · trace

Each value starts at the root, goes left if smaller and right if larger, and enters the first empty place as a leaf. 35 goes right of 30, then left of 40; 45 goes right of 40; 65 goes left of 70, then right of 60.

20354540306560807050
The tree after ten insertions. Its height is 3.
TraversalOutput
Preorder50 30 20 40 35 45 70 60 65 80
Inorder20 30 35 40 45 50 60 65 70 80
Postorder20 35 45 40 30 65 60 80 70 50

The inorder output is sorted. That is no accident but a result of the rule, and it is the fastest way to check your answer: if the inorder is not sorted, you built the tree wrong.

9Which traversal gives the values of a BST in sorted order? Which traversal is used to delete a tree (free all its nodes) and which to copy it? Why?Midterm · concept
  • Inorder gives sorted order: before each node all smaller values (the left subtree) are written, after it all larger ones (the right subtree).
  • Postorder is used to delete: a node is freed only after both its children are freed. If the root were freed first, the pointers to its children would be lost and memory would .
  • Preorder is used to copy: the node is copied first, then its children are attached to the copy. Inserting a BST's preorder output into an empty BST in the same order rebuilds the same tree.

See Postorder traversal.

10The preorder traversal of a binary search tree is 40 25 10 30 60 50 70. Draw the tree and write its postorder traversal.Final · trace

For a BST the preorder alone is enough, because the inorder is just the sorted values. A shorter way: inserting the preorder values one by one into an empty BST builds the same tree.

  1. The first value, 40, is the root.
  2. The values smaller than 40, 25, 10, 30, form the left subtree; the larger ones, 60, 50, 70, form the right subtree.
  3. In the left subtree the root is 25 with 10 on the left and 30 on the right. In the right subtree the root is 60 with 50 and 70.
10302550706040
The BST whose preorder is 40 25 10 30 60 50 70.

Postorder: 10 30 25 50 70 60 40.

3Array representation and indexes

11A binary tree is stored level by level in an array that starts at index 0. At which indexes are the children of the node at index 3 and the parent of the node at index 9? Which level is index 12 on? What would the formulas be if the array started at 1?Midterm · trace

In an array that starts at 0, the node at index i has its left child at 2i+1, its right child at 2i+2 and its parent at (i-1)/2 (integer division).

  • Children of 3: 2·3+1 = 7 and 2·3+2 = 8.
  • Parent of 9: (9-1)/2 = 4. Check: the children of 4 are 9 and 10.
  • Level k holds the indexes from 2^k - 1 to 2^(k+1) - 2. Level 3 is 7 to 14. 12 is in that range, so it is on level 3.
  • In an array that starts at 1: left 2i, right 2i+1, parent i/2. In an exam, always check where the array starts.

See A tree in an array: child and parent indexes.

12Draw the complete binary tree stored in the array [8, 3, 10, 1, 6, 14, 4, 7]. Write its preorder, inorder and postorder traversals.Midterm · trace

The array is already the : 8 is the root; 3 and 10 are on the second level; 1, 6, 14, 4 on the third; 7 is the left child (index 7) of 1 (index 3).

7163144108
The tree built from the array. It is not a BST: 14 is to the left of 10.
TraversalOutput
Preorder8 3 1 7 6 10 14 4
Inorder7 1 3 6 8 14 10 4
Postorder7 1 6 3 14 4 10 8

A common mistake is to assume the array is sorted and read it like a BST. The array layout only gives positions; it says nothing about the order of the values.

13The values 1, 2, 3, 4, 5 are inserted in this order into an empty BST, and the tree is stored in an array that starts at 0. How many cells must the array have at least? How many stay empty?Final · concept

Since the values arrive in sorted order, each one goes to the right of the previous: the tree is a chain leaning right. The right child index is 2i+2, so the nodes land at indexes 0, 2, 6, 14 and 30.

54321
A right-leaning tree: its height is 4.

The array needs at least 31 cells (indexes 0 to 30), of which only 5 are used and 26 are empty. A tree of height h needs 2^(h+1) - 1 cells in the worst case. That is why the array layout suits complete trees (a heap, for example) and wastes a lot of room for leaning trees. See The trouble with a BST in an array.

4Insert, search and delete in a binary search tree

14The values 45, 20, 70, 10, 30, 60, 90, 25, 35, 80 are inserted into an empty BST. Then 10, 20 and 45 are deleted in this order (a node with two children is replaced by its inorder successor). Draw the tree after each deletion.Final · trace
10253530206080907045
The tree after the insertions.

Deleting 10. 10 is a : the left field of its parent 20 becomes NULL and the node is freed.

253530206080907045
After deleting 10. Now 20 has only a right child.

Deleting 20. With 10 gone, 20 has one child: 30. The left field of 45 now points straight to 30; the subtree of 30 moves up as it is.

2535306080907045
After deleting 20.

Deleting 45. The root has two children. Its inorder successor is the smallest value in the right subtree: go left from 70 to 60. The value 60 is copied into the root, then 60 is deleted from the right subtree (it is a leaf).

25353080907060
After deleting 45 the root is 60.

Check: the inorder of the final tree is 25 30 35 60 70 80 90, which is sorted. See Delete: a leaf and a node with one child and Delete: a node with two children.

15In the first tree of the previous question (before the deletions), 35 and 55 are searched for. Which nodes are visited in each search, and how many comparisons are made?Midterm · trace
  • 35: 45 (smaller, go left), 20 (larger, go right), 30 (larger, go right), 35 (found). 4 nodes are visited.
  • 55: 45 (larger, go right), 70 (smaller, go left), 60 (smaller, go left), the left of 60 is NULL: not found. 3 nodes are visited.

The number of nodes visited in a search is at most the height + 1. An unsuccessful search ends at the empty place where the value would go if it were inserted: 55 would become the left child of 60. See Search.

16In what order should the numbers 1 to 7 be inserted into an empty BST to get the smallest height? What is the height if they are inserted in sorted order?Midterm · concept

The insertion order decides the shape of the tree. For the smallest height the root of every subtree must be the median of its values: 4 first, then 2 and 6, then 1, 3, 5, 7. For example 4, 2, 6, 1, 3, 5, 7 (2 and 6, or the leaves, can come in another order).

1325764
A perfect tree of height 2.

Inserted in sorted order (1, 2, ..., 7), each value goes to the right of the previous one, the tree becomes a chain and the height is 6. A search then takes O(n) instead of O(log n). See Unbalanced trees: the worst case.

17The root (50) is to be deleted from the tree of question 8. Delete it once with the inorder successor and once with the inorder predecessor. Write the preorder of both results.Final · trace

A node with two children can be replaced by two candidates: the smallest value in the right subtree (the successor) or the largest value in the left subtree (the predecessor). Both keep the BST rule.

  • Successor: go left from 70: 60. The value 60 is written into the root and 60 is deleted; its only child 65 moves to the left of 70. Preorder: 60 30 20 40 35 45 70 65 80.
  • Predecessor: go right from 30: 40, then 45. 45 is written into the root and 45 (a leaf) is deleted. Preorder: 45 30 20 40 35 70 60 65 80.

If the exam question does not say which one to use, write which one you chose. The successor or predecessor has at most one child, so the second deletion is always one of the easy cases.

5Rebuilding a tree from its traversals

18A binary tree has preorder M F C A H G P N T and inorder A C F G H M N P T. Draw the tree and write its postorder.Final · trace

The first letter of the preorder is the root. Find the root in the inorder: the letters to its left form the left subtree and those to its right the right subtree. Repeat the same step in every subtree.

  1. The root is M. In the inorder, A C F G H (5 letters) are left of M and N P T are right.
  2. In the preorder the 5 letters after M form the left subtree: F C A H G. Its root is F; in the inorder A C are left of F and G H right.
  3. In F C A H G the two letters after F are C A: the root is C and the inorder is A C, so A is the left child of C. The rest is H G: the root is H and G is its left child.
  4. The right subtree is P N T: the root is P, the inorder is N P T, so N is the left child and T the right.
ACGHFNTPM
The tree rebuilt from its preorder and inorder.

Postorder: A C G H F N T P M. See Rebuilding a tree from its traversals.

19A binary tree has postorder B D C A G F I H E and inorder A B C D E F G H I. Draw the tree and write its preorder.Final · trace

In postorder the root is the last letter. The rest works as in the previous question, except that the subtrees are taken from the front of the postorder: first the letters of the left subtree, then those of the right subtree, and the root last.

  1. The root is E. In the inorder A B C D (4 letters) are left of E and F G H I right.
  2. The first 4 letters of the postorder, B D C A, form the left subtree: its root is A. In the inorder nothing is left of A and B C D are right, so A has no left child.
  3. In B D C the root is C; the inorder is B C D, so B is the left child and D the right.
  4. The right subtree is G F I H: the root is H; the inorder is F G H I, so the left subtree is F G and the right child is I. In F G the postorder is G F: the root is F and G is its right child.
BDCAGFIHE
The tree rebuilt from its postorder and inorder.

Preorder: E A C B D H F G I.

20Can a binary tree always be rebuilt in a single way from its preorder and postorder? Show with an example.Final · concept

No. For a node with one child, these two traversals cannot tell whether the child is on the left or on the right. Both trees below have preorder A B and postorder B A.

BA
B is the left child of A. Inorder: B A.
BA
B is the right child of A. Inorder: A B.

To rebuild uniquely, one of the traversals must be the inorder (with distinct values). If the tree is known to be full, every node having 0 or 2 children, preorder and postorder are also enough.

6Expression trees

21Draw the expression tree of (a + b) * (c - d / e). Read the prefix and postfix forms off the tree.Midterm · trace

The operation done last goes to the root. Because of the parentheses * is done last; its left side is a + b and its right side c - d / e. On the right d / e is done first, so / sits deeper.

ab+cde/-*
Inner nodes are operators, leaves are operands.
  • Preorder = prefix: * + a b - c / d e
  • Postorder = postfix: a b + c d e / - *
  • Inorder without parentheses: a + b * c - d / e. Inorder gives the original expression only if every subtree is wrapped in parentheses.

See Expression trees.

22The postfix expression 5 3 + 8 2 - * is turned into an expression tree with a stack. Write the steps and compute the value of the tree.Final · trace

The rule: for a number, push a one-node tree. For an operator, pop two trees; the first popped becomes the right child and the second the left child, and the new tree is pushed.

TokenActionStack (bottom → top)
5push5
3push5, 3
+pop 3 and 5, push (5 + 3)(5+3)
8push(5+3), 8
2push(5+3), 8, 2
-pop 2 and 8, push (8 - 2)(5+3), (8-2)
*pop two trees, join them under *((5+3)*(8-2))
53+82-*
The tree built from the postfix expression.

The value is computed in postorder: first the values of the two subtrees, then the operator. 5 + 3 = 8, 8 - 2 = 6, 8 × 6 = 48. Swapping left and right gives a wrong result for - and /: it would be 2 - 8 = -6.

7Code reading

23What does the function below compute? What does it return for the tree of question 8?Midterm · code reading
def mystery(root):    if root is None:        return 0    if root.left is None and root.right is None:        return 0    return 1 + mystery(root.left) + mystery(root.right)

An empty tree and a leaf return 0; every other node adds 1 for itself. The function counts the inner nodes, the nodes with at least one child.

In the tree of question 8 the inner nodes are 50, 30, 70, 40 and 60: the result is 5. The leaves are 20, 35, 45, 65, 80; checked against the 10 nodes in total: 5 + 5 = 10.

24A student checks whether a tree is a BST with the function below. Is it correct? If not, give a counterexample and fix it.Final · code reading
def is_bst(root):    if root is None:        return True    if root.left is not None and root.left.data > root.data:        return False    if root.right is not None and root.right.data < root.data:        return False    return is_bst(root.left) and is_bst(root.right)

It is wrong. The function compares each node only with its own children. The BST rule covers the whole subtree: every value in the left subtree must be smaller than the node.

2060307050
Counterexample: 60 is in the left subtree of 50.

In this tree every node agrees with its children (60 > 30), so the function returns True. But 60 is to the left of 50, so the tree is not a BST. The fix: pass the allowed range down to every node.

def is_bst(root, low=None, high=None):    if root is None:        return True    if low is not None and root.data <= low:    # below the lower bound        return False    if high is not None and root.data >= high:  # above the upper bound        return False    return (is_bst(root.left, low, root.data) and            is_bst(root.right, root.data, high))

Going left, the node's value becomes the upper bound; going right, it becomes the lower bound. Another correct way: check that the traversal is strictly increasing.

8Code writing

25Write a recursive C function that counts the leaves of a binary tree stored with linked nodes.Midterm · code writing

There are three cases: an empty tree has 0 leaves, a childless node is 1 leaf, and otherwise the leaves of the two subtrees are added.

int countLeaves(struct TreeNode* root) {    if (root == NULL) return 0;                       // an empty tree has no leaves    if (root->left == NULL && root->right == NULL)        return 1;                                     // a childless node is a leaf    return countLeaves(root->left) + countLeaves(root->right);}

Every node is visited once: O(n) time. The recursion uses as much as the height of the tree: O(h). For the tree of question 8 the result is 5.

26Write a C function that turns a binary tree into its mirror image (swapping the left and right child of every node). What does the inorder traversal of a mirrored BST look like?Final · code writing
void mirror(struct TreeNode* root) {    if (root == NULL) return;    struct TreeNode* temp = root->left;    // swap the two children    root->left = root->right;    root->right = temp;    mirror(root->left);                    // then do the same in the subtrees    mirror(root->right);}

The function is a traversal: the swap at the node first, then the subtrees. Written in postorder it works as well. Time O(n).

In the mirror every node's larger values move to the left and the smaller ones to the right. So the inorder traversal gives the values in decreasing order: 80 70 65 60 50 45 40 35 30 20 for the tree of question 8.

27Write a Java method that checks whether two binary trees are the same (the same shape and the same values).Midterm · code writing

Two trees are the same only if both are empty, or their roots are equal and their left subtrees and right subtrees are the same too.

boolean isSame(TreeNode a, TreeNode b) {    if (a == null && b == null) return true;    // both empty    if (a == null || b == null) return false;   // one empty, the other not    return a.data == b.data        && isSame(a.left, b.left)        && isSame(a.right, b.right);}

Because && short-circuits, it stops at the first difference. In the worst case it visits every node of both trees once: O(n). Comparing a single traversal output is not enough; different trees can share one traversal, like the two trees in question 20.

9Complexity and comparison

28What are the average and worst-case time complexities of search, insert, delete and inorder traversal in a binary search tree with n nodes? When does the worst case happen?Midterm · complexity
OperationAverage (balanced)Worst (chain)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Minimum, maximumO(log n)O(n)
Inorder traversalO(n)O(n)

Search, insert and delete work on a single path from the root to a leaf, so they cost O(h). In a balanced tree h ≈ log₂ n; in a chain built by sorted or nearly sorted insertions h = n - 1. A traversal visits every node in every case. (AVL, red-black) keep the height at O(log n), which brings the worst case down to O(log n) as well.

29Compare storing a binary tree in an array and with linked nodes. When would you pick which?Final · comparison
CriterionArrayLinked nodes
Extra spaceNone; a child's place is computed from the indexTwo pointers per node, n + 1 of them NULL
Going to the parentO(1): (i-1)/2Impossible without a separate parent field
Complete treeNo gaps, very efficientWorks, with pointer overhead
Leaning treeNeeds up to 2^(h+1) - 1 cellsOnly n nodes
GrowthFixed capacity or the array is rebuiltNodes are allocated as needed
Moving a subtree (BST delete)The whole subtree is copied to new indexesOne pointer changes

If the tree always stays complete (like a heap), pick the array. For trees whose shape depends on the insertion order (like a BST), pick linked nodes. See Array or linked nodes?.

30How much extra memory do a recursive inorder traversal and a queue-based level-order traversal use? For which tree shape does each one need more memory?Final · comparison
  • A recursive traversal keeps as many frames on the as the path from the root to the current node: O(h). In a chain-shaped tree that is O(n).
  • Level order keeps at most one level's nodes in the queue at a time: O(widest level). In a perfect tree the last level holds about n/2 nodes, so that is O(n).

Recursion needs more room in a tall, thin tree and the queue in a short, wide one. Both take O(n) time. See Level-order traversal: with a queue.

10Try it

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

Show the answer

The answer is B. In every binary tree the number of leaves is one more than the number of nodes with two children: 9 + 1 = 10.

In the array layout starting at 0, at which index is the parent of the node at index 11?

Show the answer

The answer is A. The parent is at (i - 1) / 2 = 10 / 2 = 5. Check: the children of 5 are 11 and 12.

Which traversal of a BST gives the values in increasing order?

Show the answer

The answer is B. Inorder writes the left subtree (the smaller values) first, then the node, then the right subtree (the larger values).

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.