-
Notifications
You must be signed in to change notification settings - Fork 19
/
1.7. depth-first-search.py
42 lines (31 loc) · 965 Bytes
/
1.7. depth-first-search.py
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
class Node:
def __init__(self, name):
self.children = []
self.name = name
def __repr__(self):
return str(self.name)
def addChild(self, name):
self.children.append(Node(name))
return self
def depthFirstSearch(self, array):
array.append(self.name)
for n in self.children:
n.depthFirstSearch(array)
return array
if __name__ == '__main__':
root = Node('A')
root.addChild('B')
root.addChild('C')
root.addChild('D')
# append to B node E and F
root.children[0].addChild('E')
root.children[0].addChild('F')
# append to D node G and H
root.children[2].addChild('G')
root.children[2].addChild('H')
# append to F node I and J
root.children[0].children[1].addChild('I')
root.children[0].children[1].addChild('J')
# append K to G node
root.children[2].children[0].addChild('K')
print(root.depthFirstSearch([]))