Created
December 29, 2016 21:12
-
-
Save vbrown608/4f2834ed9a2c0c5cdb268debb02ec7a3 to your computer and use it in GitHub Desktop.
Depth-first searcher in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Write code that can search for a node in a tree. | |
# Return the node if it exists, and null/nil/none/undefined/false as appropriate | |
# in your language if not. For example, if the code is given "g" and a tree with | |
# the structure above, it should return the node named "g". | |
class Node: | |
def __init__(self, name, children = []): | |
self.name = name | |
self.children = children | |
def dfs_recursive(self, target): | |
if self.name == target: | |
return self | |
for child in self.children: | |
query = child.dfs_recursive(target) | |
if query != None: | |
return query | |
return None | |
def dfs_stack(root, target): | |
stack = [root] | |
while len(stack) > 0: | |
current = stack.pop() | |
if current.name == target: | |
return current | |
else: | |
stack.extend(current.children) | |
return None | |
# Create a tree: | |
# a | |
# / \ | |
# b c | |
# /|\ \ | |
# d e f g | |
# | | |
# h | |
d = Node('d') | |
e = Node('e') | |
f = Node('f') | |
h = Node('h') | |
b = Node('b', [d,e,f]) | |
g = Node('g', [h]) | |
c = Node('c', [g]) | |
a = Node('a', [b,c]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment