Skip to content

Instantly share code, notes, and snippets.

@cbdavide
Created January 3, 2017 22:48
Show Gist options
  • Save cbdavide/33e4c43f3f98b1481ff7cdc271835ac2 to your computer and use it in GitHub Desktop.
Save cbdavide/33e4c43f3f98b1481ff7cdc271835ac2 to your computer and use it in GitHub Desktop.
# Tree representation
class Node:
def __init__(self, val):
self.data = val
self.right = None
self.left = None
def recursive_inorder(node):
if not node:
return
recursive_inorder(node.left)
print(node.data, end = " ")
recursive_inorder(node.right)
def non_recursive_inorder(node):
stack = []
current = node
done = 0
while not done:
if current is not None:
stack.append(current)
current = current.left
else:
if len(stack) > 0:
current = stack.pop()
print(current.data, end = ' ')
current = current.right
else:
done = 1
# Test
if __name__ == '__main__':
a = Node(2)
b = Node(1)
c = Node(3)
a.left = b
a.right = c
recursive_inorder(a)
print()
non_recursive_inorder(a)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment