Embercode
✕
Binary TreesQuick quiz

Serialize round trips

7 questions. Covers Serialize and deserialize a binary tree.

Questions 1 to 5 of 7

  1. 1. What does this print? ``cpp auto t = node(8, node(3, leaf(1), nullptr), leaf(9)); std::cout << serialize(t.get()) << '\n'; ` node and leaf are the helpers from this lesson, and serialize writes the tree in preorder with #` markers for empty spots.
  2. 2. What does this print? ``cpp auto r = deserialize("12abc,#,#"); std::cout << r->value << '\n'; ` deserialize is the reader from this lesson, and it reads each token with std::stoi`.
  3. 3. A tree has 6 real nodes. How many # markers does its serialized text have?
  4. 4. Two trees each have a root 1 and one child 2. In one, 2 is the left child. In the other, 2 is the right child. Which pair of texts from serialize tells them apart?
  5. 5. Spot the bug. This reader should rebuild the tree from 1,2,#,#,#, but writing the result back out gives 1,2,#,#,2,#,#. ``cpp std::unique_ptr<Node> read_node_wrong(const std::vector<std::string>& tokens, std::size_t pos) { if (pos >= tokens.size()) throw std::runtime_error("ran out of tokens"); const std::string& token = tokens[pos++]; if (token == "#") return nullptr; auto current = std::make_unique<Node>(std::stoi(token)); current->left = read_node_wrong(tokens, pos); current->right = read_node_wrong(tokens, pos); return current; } `` What is the bug?

5 question(s) left on this page.