Created
June 17, 2019 01:38
-
-
Save alexminnaar/35c3959b671c8761af343ff1d4a3dd92 to your computer and use it in GitHub Desktop.
depth-first search
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
class Node: | |
def __init__(self, x): | |
self.val = x | |
self.children = [] | |
def dfs(node, target): | |
# if the node is found then return it | |
if node.val == target: | |
return node | |
if node.children: | |
for child in node.children: | |
# if the child is the target the child node will be returned, if not then False will be returned | |
res = dfs(child, target) | |
# if False then don't return anything and continue searching | |
if res: | |
return res | |
return False | |
#create tree | |
a = Node("a") | |
b = Node("b") | |
c = Node("c") | |
d = Node("d") | |
e = Node("e") | |
f = Node("f") | |
g = Node("g") | |
h = Node("h") | |
a.children = [b, c] | |
b.children = [d, e, f] | |
c.children = [g] | |
g.children = [h] | |
#search from the root for the given target | |
node = dfs(a, "g") | |
if node: | |
print node.val | |
else: | |
print node |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment