1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 5

CAP7004 · Unit 5: Trees

Binary trees and traversals

8 practice questions

Key points

  • Preorder root-L-R, inorder L-root-R, postorder L-R-root
  • Level order uses a queue
  • Max nodes at height h is 2^(h+1) - 1
  • Inorder + preorder/postorder reconstructs the tree

A binary tree has nodes with at most two children (left and right). Terms: root (top), leaf (no children), height (edges on the longest root-to-leaf path; a single node has height 0), depth of a node (edges from the root), level (depth + 1 in many texts).

Counting facts: level L (root at 0) has at most 2^L nodes; a tree of height h has at most 2^(h+1) - 1 nodes (15 for h = 3). In a full binary tree (every node has 0 or 2 children), leaves = internal nodes + 1.

Traversals of the tree with root 1, children 2 and 3, node 2 having children 4 and 5, node 3 having right child 6:

  • Preorder (root, left, right): 1 2 4 5 3 6
  • Inorder (left, root, right): 4 2 5 1 3 6
  • Postorder (left, right, root): 4 5 2 6 3 1
  • Level order (breadth first, uses a queue): 1 2 3 4 5 6
def inorder(n):
    return inorder(n.left) + [n.v] + inorder(n.right) if n else []

Each traversal visits n nodes: O(n) time; recursion uses O(h) stack.

Reconstruction: inorder plus either preorder or postorder identifies a unique tree. Preorder alone does not. The first preorder item (or last postorder item) is the root; find it in inorder to split left and right.

Exam pitfall: do not confuse height measured in edges with height measured in nodes; state which convention is used.

Try two questions

Question 1 · Tier 1, Recall

A node with no children is called a:

  1. Root
  2. Parent
  3. Leaf
  4. Sibling
Show the answer

C. Leaves have no left or right child.

Question 2 · Tier 3, Apply

The maximum number of nodes in a binary tree of height 3 (height counted in edges) is:

  1. 16
  2. 8
  3. 7
  4. 15
Show the answer

D. 1 + 2 + 4 + 8 = 15 = 2^4 - 1.