codekofi
← All problems

Problem 82

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Node {
2 int val;
3 Node* left;
4 Node* right;
5};
6
7vector<optional<int>> spill(Node* root) {
8
9 vector<optional<int>> out;
10
11 if (!root) {
12 return out;
13 }
14
15 queue<Node*> q;
16 q.push(root);
17
18 while (!q.empty()) {
19
20 Node* node = q.front();
21 q.pop();
22
23 if (!node) {
24 out.push_back(nullopt);
25 continue;
26 }
27
28 out.push_back(node->val);
29 q.push(node->left);
30 q.push(node->right);
31 }
32
33 while (!out.empty() && !out.back()) {
34 out.pop_back();
35 }
36
37 return out;
38}
39
40Node* raise(const vector<int>& pre, int& at,
41 const vector<int>& in, int lo, int hi) {
42
43 if (lo > hi) {
44 return nullptr;
45 }
46
47 int value = pre[at];
48 at++;
49
50 int cut = lo;
51
52 while (in[cut] != value) {
53 cut++;
54 }
55
56 Node* node = new Node{value, nullptr, nullptr};
57
58 node->left = raise(pre, at, in, lo, cut - 1);
59 node->right = raise(pre, at, in, cut + 1, hi);
60
61 return node;
62}
63
64vector<optional<int>> solution(const vector<int>& pre,
65 const vector<int>& in) {
66
67 int at = 0;
68 int n = in.size();
69
70 Node* root = raise(pre, at, in, 0, n - 1);
71
72 return spill(root);
73}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.