From faf16d7ced7f563bb0c92265bef27b6664156fb5 Mon Sep 17 00:00:00 2001 From: Gini5 Date: Sat, 9 Feb 2019 09:54:07 +0800 Subject: [PATCH] Add iteration version (#322) --- traversals/binary_tree_traversals.py | 58 +++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/traversals/binary_tree_traversals.py b/traversals/binary_tree_traversals.py index cbcaf08b7..9afe0cac4 100644 --- a/traversals/binary_tree_traversals.py +++ b/traversals/binary_tree_traversals.py @@ -46,7 +46,6 @@ 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 @@ -54,7 +53,6 @@ def pre_order(node): pre_order(node.left) pre_order(node.right) - def in_order(node): if not isinstance(node, TreeNode) or not node: return @@ -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") @@ -104,3 +146,15 @@ if __name__ == '__main__': 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") \ No newline at end of file