-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTreeInput.cpp
More file actions
56 lines (46 loc) · 1.33 KB
/
TreeInput.cpp
File metadata and controls
56 lines (46 loc) · 1.33 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
#include <iostream>
#include <queue>
#include "../TreeNode.h"
using namespace std;
TreeNode<int>* takeInputLevelWise() {
int rootData;
cout << "Enter root data:";
cin >> rootData;
auto root = new TreeNode<int>(rootData);
queue<TreeNode<int>*> pendingNodes;
pendingNodes.push(root);
while (!pendingNodes.empty()) {
TreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
cout << "Enter number of children of " << front->data << ":";
int numChild;
cin >> numChild;
for (int i = 0; i < numChild; i++) {
int childData;
cout << "Enter " << i << "th child of " << front->data << ":";
cin >> childData;
auto childNode = new TreeNode<int>(childData);
front->children.push_back(childNode);
pendingNodes.push(childNode);
}
}
return root;
}
void printTree(TreeNode<int>* root) {
if (root == nullptr) {
return;
}
cout << root->data << ":";
for (int i = 0; i < root->children.size(); i++) {
cout << root->children.at(i)->data << ",";
}
cout << endl;
for (int i = 0; i < root->children.size(); i++) {
printTree(root->children.at(i));
}
}
int main() {
TreeNode<int>* root = takeInputLevelWise();
printTree(root);
return 0;
}