Embercode
✕
Binary TreesQuick quiz

Tree DP

6 questions. Covers Tree DP: return two values per node.

Questions 1 to 5 of 6

  1. 1. A node is not chosen. Why does its without value add the larger of with and without for each child?
  2. 2. The tree below has weights 5 at the root, 1 on the left, 6 on the right, and 2 under the 1. Which set of nodes gives the best total? ``text 5 / \ 1 6 / 2 ``
  3. 3. This program runs the tree DP on a small tree. ``cpp #include <algorithm> #include <iostream> #include <memory> #include <utility> struct Node { long long value; std::unique_ptr<Node> left; std::unique_ptr<Node> right; }; std::unique_ptr<Node> make(long long value, std::unique_ptr<Node> left = nullptr, std::unique_ptr<Node> right = nullptr) { auto node = std::make_unique<Node>(); node->value = value; node->left = std::move(left); node->right = std::move(right); return node; } struct Best { long long with; // best total when this node is chosen long long without; // best total when this node is not chosen }; Best solve(const Node* n) { if (!n) return {0, 0}; Best l = solve(n->left.get()); Best r = solve(n->right.get()); return {n->value + l.without + r.without, std::max(l.with, l.without) + std::max(r.with, r.without)}; } int main() { auto root = make(4, make(9, make(1)), make(2, nullptr, make(6))); Best b = solve(root.get()); std::cout << "best: " << std::max(b.with, b.without) << '\n'; } `` What does it print?
  4. 4. This program prints the root's with value as the answer, and also prints the correct answer. ``cpp #include <algorithm> #include <iostream> #include <memory> #include <utility> struct Node { long long value; std::unique_ptr<Node> left; std::unique_ptr<Node> right; }; std::unique_ptr<Node> make(long long value, std::unique_ptr<Node> left = nullptr, std::unique_ptr<Node> right = nullptr) { auto node = std::make_unique<Node>(); node->value = value; node->left = std::move(left); node->right = std::move(right); return node; } struct Best { long long with; // best total when this node is chosen long long without; // best total when this node is not chosen }; Best solve(const Node* n) { if (!n) return {0, 0}; Best l = solve(n->left.get()); Best r = solve(n->right.get()); return {n->value + l.without + r.without, std::max(l.with, l.without) + std::max(r.with, r.without)}; } int main() { auto root = make(1, make(8, make(5)), make(9)); Best s = solve(root.get()); std::cout << "buggy: " << s.with << " correct: " << std::max(s.with, s.without) << '\n'; } `` What does it print?
  5. 5. Which statements about the tree DP method in this lesson are true? Pick all that apply.

    Pick every answer that is true.

5 question(s) left on this page.