Skip to content

Add iteration version for Binary Tree Traverse #322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 9, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions traversals/binary_tree_traversals.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,13 @@ def build_tree():
node_found.right = right_node
q.put(right_node)


def pre_order(node):
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=" ")
pre_order(node.left)
pre_order(node.right)


def in_order(node):
if not isinstance(node, TreeNode) or not node:
return
Expand Down Expand Up @@ -84,6 +82,50 @@ def level_order(node):
if node_dequeued.right:
q.put(node_dequeued.right)

#iteration version
def pre_order_iter(node):
if not isinstance(node, TreeNode) or not node:
return
stack = []
n = node
while n or stack:
while n: #start from root node, find its left child
print(n.data, end=" ")
stack.append(n)
n = n.left
#end of while means current node doesn't have left child
n = stack.pop()
#start to traverse its right child
n = n.right

def in_order_iter(node):
if not isinstance(node, TreeNode) or not node:
return
stack = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=" ")
n = n.right

def post_order_iter(node):
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: #to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: #pop up from stack2 will be the post order
print(stack2.pop().data, end=" ")

if __name__ == '__main__':
print("\n********* Binary Tree Traversals ************\n")
Expand All @@ -104,3 +146,15 @@ def level_order(node):
print("\n********* Level Order Traversal ************")
level_order(node)
print("\n******************************************\n")

print("\n********* Pre Order Traversal - Iteration Version ************")
pre_order_iter(node)
print("\n******************************************\n")

print("\n********* In Order Traversal - Iteration Version ************")
in_order_iter(node)
print("\n******************************************\n")

print("\n********* Post Order Traversal - Iteration Version ************")
post_order_iter(node)
print("\n******************************************\n")