-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchildSum.cpp
134 lines (117 loc) · 2.93 KB
/
childSum.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
using namespace std;
class Tree {
private:
int vertices;
vector<list<int> > array;
vector<int> weights;
vector<bool> visited;
queue<int> dfsQueue;
public:
Tree(int v) {
array.resize(v);
weights.resize(v);
vertices = v;
visited.resize(v, false);
}
void addEdge(int source, int destination) {
if (source < vertices && destination < vertices)
array[source].push_front(destination);
}
void printTree() {
cout << "Adjacency List of Tree:" <<endl;
list<int>::iterator temp;
for(int i=0; i<vertices; i++) {
cout << "|" << i << "| => ";
temp = (array[i]).begin();
while(temp != array[i].end()) {
cout << "[" <<*temp << "] -> ";
temp++;
}
cout <<"NULL"<<endl;
}
}
void dfs(int at) {
if (visited[at]) {
return;
}
cout << at << ' ';
visited[at] = true;
list<int>::iterator it;
for (it = array[at].begin(); it != array[at].end(); it++) {
dfs(*it);
}
visited.resize(vertices, false);
}
void dfsTraversal() {
cout << "DFS Traversal" << endl;
for (int i = 0; i < vertices; i++) {
dfs(i);
}
cout << endl;
}
void bfs(int at) {
dfsQueue.push(at);
visited[at] = true;
while(!dfsQueue.empty()) {
int currNode = dfsQueue.front();
cout << currNode << ' ';
dfsQueue.pop();
list<int>::iterator it = array[currNode].begin();
for (it; it != array[currNode].end(); it++) {
if (!visited[*it]) {
dfsQueue.push(*it);
visited[*it] = true;
}
}
}
}
void bfsTraversal() {
cout << "BFS Traversal" << endl;
for (int i = 0; i < vertices; i++) {
bfs(i);
}
cout << endl;
}
void addWeigths() {
for (int i = 0; i < vertices; i++) {
cout << "Enter Weight for " << i << " Node : ";
cin >> weights[i];
}
}
int findSum() {
int sum = 0;
for (int i = 0; i < vertices; i++) {
if (array[i].empty()) {
sum += weights[i];
}
}
cout << "Sum of leaf nodes is: " << sum << endl;
return sum;
}
};
int main() {
Tree g(11);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
g.addEdge(2, 6);
g.addEdge(2, 7);
g.addEdge(3, 8);
g.addEdge(3, 9);
g.addEdge(6, 10);
cout << endl;
g.printTree();
g.dfsTraversal();
g.bfsTraversal();
g.addWeigths();
g.findSum();
cout << endl;
return 0;
}