codekofi
← All problems

Problem 43

Hard

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
7Node* build(const vector<optional<int>>& level) {
8
9 if (level.empty() || !level[0]) {
10 return nullptr;
11 }
12
13 Node* root = new Node{*level[0], nullptr, nullptr};
14
15 queue<Node*> q;
16 q.push(root);
17
18 int i = 1;
19 int n = level.size();
20
21 while (!q.empty() && i < n) {
22
23 Node* node = q.front();
24 q.pop();
25
26 if (level[i]) {
27 node->left = new Node{*level[i], nullptr, nullptr};
28 q.push(node->left);
29 }
30
31 i++;
32
33 if (i < n && level[i]) {
34 node->right = new Node{*level[i], nullptr, nullptr};
35 q.push(node->right);
36 }
37
38 i++;
39 }
40
41 return root;
42}
43
44vector<optional<int>> spill(Node* root) {
45
46 vector<optional<int>> out;
47
48 if (!root) {
49 return out;
50 }
51
52 queue<Node*> q;
53 q.push(root);
54
55 while (!q.empty()) {
56
57 Node* node = q.front();
58 q.pop();
59
60 if (!node) {
61 out.push_back(nullopt);
62 continue;
63 }
64
65 out.push_back(node->val);
66 q.push(node->left);
67 q.push(node->right);
68 }
69
70 while (!out.empty() && !out.back()) {
71 out.pop_back();
72 }
73
74 return out;
75}
76
77void write(Node* node, string& out) {
78
79 if (!node) {
80 out += "#,";
81 return;
82 }
83
84 out += to_string(node->val);
85 out += ',';
86
87 write(node->left, out);
88 write(node->right, out);
89}
90
91Node* read(const string& text, int& at) {
92
93 string token;
94
95 while (text[at] != ',') {
96 token += text[at];
97 at++;
98 }
99
100 at++;
101
102 if (token == "#") {
103 return nullptr;
104 }
105
106 Node* node = new Node{stoi(token), nullptr, nullptr};
107
108 node->left = read(text, at);
109 node->right = read(text, at);
110
111 return node;
112}
113
114pair<string, vector<optional<int>>> solution(
115 const vector<optional<int>>& level) {
116
117 string text;
118 write(build(level), text);
119
120 int at = 0;
121 Node* again = read(text, at);
122
123 return {text, spill(again)};
124}

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.