-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprogram.gen
More file actions
136 lines (105 loc) · 2.38 KB
/
program.gen
File metadata and controls
136 lines (105 loc) · 2.38 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
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
135
136
object queue {
var data = [];
}
func queue_is_empty(var queue) {
return |queue.data| == 0;
}
func queue_enqueue(var queue, var value) {
var new_queue = [value];
var i = 0;
while (i < |queue.data|) {
new_queue = new_queue + queue.data[i];
i = i + 1;
}
queue.data = new_queue;
}
func queue_dequeue(var queue) {
var value = queue.data[|queue.data| - 1];
queue.data = queue.data - 1;
return value;
}
object stack {
var data = [];
}
func stack_is_empty(var stack) {
return |stack.data| == 0;
}
func stack_push(var stack, var value) {
stack.data = stack.data + value;
}
func stack_pop(var stack) {
var value = stack.data[|stack.data| - 1];
stack.data = stack.data - 1;
return value;
}
object node {
var value;
var children = [];
}
func node_create(var value) {
var node = new node;
node.value = value;
return node;
}
func tree_create() {
var r = node_create(1);
var rl = node_create(2);
var rr = node_create(3);
var rll = node_create(4);
var rlr = node_create(5);
var rrl = node_create(6);
var rrr = node_create(7);
rl.children = [rll, rlr];
rr.children = [rrl, rrr];
r.children = [rl, rr];
return r;
}
func bfs(var root) {
var queue = new queue;
queue_enqueue(queue, root);
while (!queue_is_empty(queue)) {
var node = queue_dequeue(queue);
print node.value;
print " ";
var i = 0;
while (i < |node.children|) {
queue_enqueue(queue, node.children[i]);
i = i + 1;
}
}
}
func dfs(var root) {
var stack = new stack;
stack_push(stack, root);
while (!stack_is_empty(stack)) {
var node = stack_pop(stack);
print node.value;
print " ";
var i = 0;
while (i < |node.children|) {
stack_push(stack, node.children[|node.children| - 1 - i]);
i = i + 1;
}
}
}
func dfs_recursive(var root) {
print root.value;
print " ";
var i = 0;
while (i < |root.children|) {
dfs_recursive(root.children[i]);
i = i + 1;
}
}
func main() {
var root = tree_create();
print "BFS using Queue: ";
bfs(root);
print "" endl;
print "DFS using Stack: ";
dfs(root);
print "" endl;
print "DFS using Recursion: ";
dfs_recursive(root);
print "";
}