Embercode
✕
Binary TreesQuick quiz

Maximum path sum

6 questions. Covers Maximum path sum with negative values.

Questions 1 to 5 of 6

  1. 1. In the maximum path sum method, why does a node send only its value plus the larger clipped child gain up to its parent, not the sum of both children?
  2. 2. A child has gain -4. What does clipping do to it?
  3. 3. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <limits> #include <memory> struct Node { int val = 0; std::unique_ptr<Node> left, right; }; std::unique_ptr<Node> mk(int v, std::unique_ptr<Node> l = nullptr, std::unique_ptr<Node> r = nullptr) { auto n = std::make_unique<Node>(); n->val = v; n->left = std::move(l); n->right = std::move(r); return n; } long long gain(const Node* n, long long& best) { if (n == nullptr) return 0; long long left = std::max(0LL, gain(n->left.get(), best)); long long right = std::max(0LL, gain(n->right.get(), best)); best = std::max(best, n->val + left + right); return n->val + std::max(left, right); } long long maxPathSum(const Node* root) { long long best = std::numeric_limits<long long>::min(); gain(root, best); return best; } int main() { auto t = mk(5, mk(3), mk(-4)); std::cout << maxPathSum(t.get()) << '\n'; } ``
  4. 4. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <limits> #include <memory> struct Node { int val = 0; std::unique_ptr<Node> left, right; }; std::unique_ptr<Node> mk(int v, std::unique_ptr<Node> l = nullptr, std::unique_ptr<Node> r = nullptr) { auto n = std::make_unique<Node>(); n->val = v; n->left = std::move(l); n->right = std::move(r); return n; } long long gain(const Node* n, long long& best) { if (n == nullptr) return 0; long long left = std::max(0LL, gain(n->left.get(), best)); long long right = std::max(0LL, gain(n->right.get(), best)); best = std::max(best, n->val + left + right); return n->val + std::max(left, right); } long long maxPathSum(const Node* root) { long long best = std::numeric_limits<long long>::min(); gain(root, best); return best; } int main() { auto t = mk(-3, mk(-1), mk(-2)); std::cout << maxPathSum(t.get()) << '\n'; } ``
  5. 5. True or false: if every value in the tree is negative, maxPathSum returns 0, because clipping sets every gain to 0.

5 question(s) left on this page.