-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathassign3.cpp
74 lines (61 loc) · 1.94 KB
/
assign3.cpp
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
/*A book consists of chapters, chapters consist of sections and sections consist of subsections.
Construct a tree and print the nodes. Find the time and space requirements of your method.*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Node
{
public:
string name;
vector<Node *> children;
Node(string name)
{
this->name = name;
}
};
void printNodes(Node *node, int depth)
{
for (int i = 0; i < depth; i++)
{
cout << " ";
}
cout << "- " << node->name << endl;
for (Node *child : node->children)
{
printNodes(child, depth + 1);
}
}
int main()
{
// Create the tree structure
// Added root node book
Node *book = new Node("Book");
// Added child Chapters
Node *chapter1 = new Node("Chapter 1");
Node *chapter2 = new Node("Chapter 2");
book->children.push_back(chapter1);
book->children.push_back(chapter2);
// Added child sections to Chapters
Node *section1_1 = new Node("Section 1.1");
Node *section1_2 = new Node("Section 1.2");
chapter1->children.push_back(section1_1);
chapter1->children.push_back(section1_2);
Node *section2_1 = new Node("Section 2.1");
chapter2->children.push_back(section2_1);
Node *section2_2 = new Node("Section 2.2");
chapter2->children.push_back(section2_2);
// Added child sub-sections to sections
Node *subSection1_1_1 = new Node("Sub-section 1.1.1");
section1_1->children.push_back(subSection1_1_1);
Node *subSection1_1_2 = new Node("Sub-section 1.1.2");
section1_1->children.push_back(subSection1_1_2);
Node *subSection2_2_1 = new Node("Sub-section 2.2.1");
section2_2->children.push_back(subSection2_2_1);
Node *subSection2_2_2 = new Node("Sub-section 2.2.2");
section2_2->children.push_back(subSection2_2_2);
// Print the nodes of the tree
printNodes(book, 0);
cout << "Code by Pranav Mehendale" << endl;
return 0;
}