-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem84.cpp
More file actions
70 lines (59 loc) · 1.45 KB
/
problem84.cpp
File metadata and controls
70 lines (59 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class SortedArrayToBST {
vector<int> nums;
public:
void readInput() {
string line;
getline(cin, line);
istringstream iss(line);
int num;
while (iss >> num) nums.push_back(num);
}
TreeNode* buildBST(int left, int right) {
if (left > right) return NULL;
int mid = left + (right - left) / 2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = buildBST(left, mid - 1);
node->right = buildBST(mid + 1, right);
return node;
}
vector<string> levelOrder(TreeNode* root) {
vector<string> result;
if (!root) return result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* curr = q.front(); q.pop();
if (curr) {
result.push_back(to_string(curr->val));
q.push(curr->left);
q.push(curr->right);
} else {
result.push_back("null");
}
}
while (!result.empty() && result.back() == "null") result.pop_back();
return result;
}
void display() {
TreeNode* root = buildBST(0, nums.size() - 1);
vector<string> level = levelOrder(root);
for (int i = 0; i < level.size(); ++i) {
if (i) cout << " ";
cout << level[i];
}
cout << endl;
}
};
int main() {
SortedArrayToBST solver;
solver.readInput();
solver.display();
return 0;
}