-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdepth_first_search.py
43 lines (37 loc) · 1.06 KB
/
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
43
"""
Implementing Depth First Search
"""
# Do not edit the class below except
# for the depthFirstSearch method.
# Feel free to add new properties
# and methods to the class.
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
def depthFirstSearch(self, array):
# Using a stack (LIFO) approach.
stack = [self]
while stack:
node = stack.pop()
array.append(node.name)
stack.extend(reversed(node.children))
return array
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
# Time complexity is O(v + e) | Space complexity is O(v)
def depthFirstSearch(self, array):
# Using recursion.
node = self.name
array.append(node)
for child in self.children:
child.depthFirstSearch(array)
return array