-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinputBinaryTree.cpp
More file actions
57 lines (54 loc) · 1.53 KB
/
Copy pathinputBinaryTree.cpp
File metadata and controls
57 lines (54 loc) · 1.53 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
// Not a Leetcode question
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
TreeNode* buildTree(vector<string>& nodes, int& index) {
cout << nodes.size();
if (index >= nodes.size() || nodes[index] == "null") {
index++;
return nullptr;
}
int currNode = stoi(nodes[index]);
TreeNode* root = new TreeNode(currNode);
index++;
root->left = buildTree(nodes, index);
root->right = buildTree(nodes, index);
return root;
}
int main() {
vector<string> nodes;
string node;
cout << "Input binary tree:" << endl;
while (cin >> node && node != "end") {
nodes.push_back(node);
}
int index = 0;
TreeNode* root = buildTree(nodes, index);
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
cout << endl << "Binary tree:" << endl;
while (!nodeQueue.empty()) {
TreeNode* currNode = nodeQueue.front();
if (currNode) {
cout << currNode->val << " ";
if (currNode->right) {
nodeQueue.push(currNode->right);
}
if (currNode->left) {
nodeQueue.push(currNode->left);
}
} else {
cout << "NULL" << " ";
}
nodeQueue.pop();
}
}