Created
January 3, 2017 22:48
-
-
Save cbdavide/33e4c43f3f98b1481ff7cdc271835ac2 to your computer and use it in GitHub Desktop.
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
# 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