Data Structures and Algorithms

A binary heap is stored in an array a[0], a[1], a[2], … with the root at a[0], filling each level from left to right starting at the top. Which are the children and the parent of a[4]?

  1. AChildren a[9] and a[10]; parent a[1]
  2. BChildren a[8] and a[9]; parent a[2]
  3. CChildren a[9] and a[10]; parent a[2]
Show answer and explanation

Answer: A. Children a[9] and a[10]; parent a[1]

With the root at a[0], the children of a[i] are a[2i+1] and a[2i+2], and its parent is a[(i−1) ÷ 2, rounded down]. For i = 4, the children are a[9] and a[10] and the parent is a[(4−1) ÷ 2] = a[1]. With the root at a[1], the children are a[2i] and a[2i+1] and the parent is a[i ÷ 2], so it is important to check which convention is being used. Because a heap is a complete binary tree, it can be stored in an array without pointers, and parents and children are found by index arithmetic alone.

  • A. Correct. The children are 2×4+1 = 9 and 2×4+2 = 10, and the parent is (4−1) ÷ 2 = 1.
  • B. This applies the formulas for a root at a[1] (children 2i and 2i+1, parent i ÷ 2).
  • C. The children are right, but the parent is (4−1) ÷ 2 rounded down, which is a[1].
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. A max-heap, in which each parent's value is at least as large as its children's, is stored in an array with the root at a[0]. 45 is added to the heap 50, 30, 40, 10, 20, 35 by placing it at the end and then swapping it with its parent as long as it is larger than the parent. What is the resulting array?
  2. When a binary search tree is traversed in in-order (visiting the left subtree, then the node, then the right subtree), how are the values of the visited nodes ordered? Assume all values are distinct.
  3. The values 50, 30, 70, 20, 40, 60, 80 are inserted in this order into an empty binary search tree. In what order are the nodes visited when the tree is traversed in post-order (left subtree, right subtree, then the node)?
  4. The values 1, 2, 3, …, 1000 are inserted in this order into an empty binary search tree (no rebalancing is done). When searching this tree for 1000, how many nodes are compared, starting from the root, before it is found?
  5. What is the main reason that B-trees (including B+ trees), rather than binary search trees, are widely used for indexes in databases and file systems?