forked from Amitshu2003/All-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeUse.cpp
More file actions
75 lines (66 loc) · 1.72 KB
/
TreeUse.cpp
File metadata and controls
75 lines (66 loc) · 1.72 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
71
72
73
74
#include <iostream>
#include <queue>
#include "TreeNode.h"
using namespace std;
TreeNode<int>* takeInputLevelWise() {
int rootData;
cout << "Enter root data" << endl;
cin >> rootData;
TreeNode<int>* root = new TreeNode<int>(rootData);
queue<TreeNode<int>*> pendingNodes;
pendingNodes.push(root);
while (pendingNodes.size() != 0) {
TreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
cout << "Enter num of children of " << front->data << endl;
int numChild;
cin >> numChild;
for (int i = 0; i < numChild; i++) {
int childData;
cout << "Enter " << i << "th child of " << front->data << endl;
cin >> childData;
TreeNode<int>* child = new TreeNode<int>(childData);
front->children.push_back(child);
pendingNodes.push(child);
}
}
return root;
}
TreeNode<int>* takeInput() {
int rootData;
cout << "Enter data" << endl;
cin >> rootData;
TreeNode<int>* root = new TreeNode<int>(rootData);
int n;
cout << "Enter num of children of " << rootData << endl;
cin >> n;
for (int i = 0; i < n; i++) {
TreeNode<int>* child = takeInput();
root->children.push_back(child);
}
return root;
}
void printTree(TreeNode<int>* root) {
if (root == NULL) {
return;
}
cout << root->data << ":";
for (int i = 0; i < root->children.size(); i++) {
cout << root->children[i]->data << ",";
}
cout << endl;
for (int i = 0; i < root->children.size() ; i++) {
printTree(root->children[i]);
}
}
int main() {
/*TreeNode<int>* root = new TreeNode<int>(1);
TreeNode<int>* node1 = new TreeNode<int>(2);
TreeNode<int>* node2 = new TreeNode<int>(3);
root->children.push_back(node1);
root->children.push_back(node2);
*/
TreeNode<int>* root = takeInputLevelWise();
printTree(root);
// TODO delete the tree
}