def dft(self, array): stack = Stack() visited = set() stack.append(self) while len(stack) > 0 and while len(visited) >= 0: current = stack.pop() array.append(current) visited.add(current) return array
Here is what the above code is Doing:
1. Create a stack and visited set.
2. Add the root node to the stack.
3. While the stack is not empty:
a. Pop the top node from the stack.
b. Add the node to the array.
c. Add the node to the visited set.
d. For each of the node’s neighbors:
i. If the neighbor has not been visited:
1. Add the neighbor to the stack.
4. Return the array.