Embercode
✕
Binary TreesQuick quiz

Tree bug hunt

8 questions. Covers Debugging lab: tree recursion bugs.

Questions 1 to 5 of 8

  1. 1. The Node struct is the one from the lesson (value, left, right). What does this program print? ``cpp int heightBugBase(const Node* n) { if (n == nullptr) return 1; return 1 + std::max(heightBugBase(n->left.get()), heightBugBase(n->right.get())); } int main() { Node a(1); std::cout << heightBugBase(&a) << std::endl; a.right = std::make_unique<Node>(3); std::cout << heightBugBase(&a) << std::endl; } ``
  2. 2. This function should return the height of a tree in edges, but it is wrong for some trees. Which tree gives a wrong answer? ``cpp int heightBugLeft(const Node* n) { if (n == nullptr) return -1; return 1 + heightBugLeft(n->left.get()); } ``
  3. 3. The sum of the test tree should be 36, but this function returns 13 for it. What is the bug? ``cpp int sumBugRight(const Node* n) { if (n == nullptr) return 0; return n->value + sumBugRight(n->left.get()); } ``
  4. 4. The program calls countLeavesBug(root.get()) twice on the test tree and prints leafCount after each call. The first line says 2 and the second says 4. Why? ``cpp int leafCount = 0; void countLeavesBug(const Node* n) { if (n == nullptr) return; if (n->left == nullptr && n->right == nullptr) ++leafCount; countLeavesBug(n->left.get()); countLeavesBug(n->right.get()); } ``
  5. 5. Calling countNodesBug on the test tree makes the program exit with code 139 and print nothing. What is the cause? ``cpp int countNodesBug(const Node* n) { return 1 + countNodesBug(n->left.get()) + countNodesBug(n->right.get()); } ``

5 question(s) left on this page.