Skip to content

Instantly share code, notes, and snippets.

@georgeteo
Last active September 24, 2015 00:04
Show Gist options
  • Save georgeteo/44f8c93d03d654d1fa51 to your computer and use it in GitHub Desktop.
Save georgeteo/44f8c93d03d654d1fa51 to your computer and use it in GitHub Desktop.
Python Graph-Tree Implementation
from Queue import Queue
class graph(object):
'''Implementation of a graph'''
def __init__(self, data, children=[]):
self.data = data
self.visited = False
self.children = children
def queue_bfs(self):
''' Initialize queue and put root node in queue'''
q = Queue()
q.put(self)
while not q.empty():
''' Get node '''
node = q.get()
if node.visited == False:
''' If already visited this node, skip '''
continue
''' Else do stuff to this node and set visited = True'''
node.visited = True
''' Add children to queue'''
for child in node.children:
q.put(child)
def recursive_dfs(self):
if len(self.children) == 0:
''' If leaf node, do BC stuff'''
return
if self.visited == True:
'''Q: what to return if already visited?'''
return
recursive_return_values = []
for child in self.children:
recursive_return_values.append(child.recursive_dfs())
''' Do stuff to the recursive return values and return a value'''
return
def stack_dfs(self):
''' Initialize the stack (list) and put root node inside'''
s = []
s.append(self)
while len(s) != 0:
'''Get top of the stack'''
node = s.pop()
if node.visited == True:
'''If already visited, skip'''
continue
'''Else, do stuff to node'''
'''Add children to stack'''
s += node.children
class tree(object):
'''Now implement a binary tree.
Similar to above but must check for None nodes'''
def __init__(self, data, right=None, left=None):
self.data = data
self.right=right
self.left=left
def queue_bft(self):
q=Queue()
q.put(self)
if not q.empty():
node = q.get()
if node is None:
continue
''' Do stuff to node'''
if node.left != None: # Q: These lines are redundant?
q.put(node.left)
if node.right != None:
q.put(node.right)
def recursive_dfs(self):
if self.left is None and self.right is None:
'''If leaf node.
Q: is there a better way?
'''
'''Do Base Case stuff'''
return
'''Recurse left subtree'''
if self.left is not None:
'''Q: Can use try, except flow instead?'''
left_subtree_return_value = self.left.recursive_dfs()
if self.right is not None:
right_subtree_return_value = self.right.recursive_dfs()
''' Do stuff with left and right values'''
return
def stack_dfs(self):
s = []
s.append(self)
while s:
node = s.pop()
if node == None:
continue
''' Do stuff to node'''
s.append(node.left) # Q: is it better to check if left and right child are not None here?
s.append(node.right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment