Iterative Preorder Traversal
Given a Binary Tree, write an iterative function to print Preorder traversal of the given binary tree.
Refer this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedures to iterative, we need an explicit stack. Following is a simple stack based iterative process to print Preorder traversal.
1) Create an empty stack nodeStack and push root node to stack.
2) Do following while nodeStack is not empty.
….a) Pop an item from stack and print it.
….b) Push right child of popped item to stack
….c) Push left child of popped item to stack
Right child is pushed before left child to make sure that left subtree is processed first.
# Python program to perform iterative preorder traversal
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# An iterative process to print preorder traveral of BT
def iterativePreorder(root):
# Base CAse
if root is None:
return
# create an empty stack and push root to it
nodeStack = []
nodeStack.append(root)
# Pop all items one by one. Do following for every popped item
# a) print it
# b) push its right child
# c) push its left child
# Note that right child is pushed first so that left
# is processed first */
while(len(nodeStack) > 0):
# Pop the top item from stack and print it
node = nodeStack.pop()
print node.data,
# Push right and left children of the popped node
# to stack
if node.right is not None:
nodeStack.append(node.right)
if node.left is not None:
nodeStack.append(node.left)
# Driver program to test above function
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
iterativePreorder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
References:
https://www.geeksforgeeks.org/iterative-preorder-traversal/
My codes
class Solution1(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
output.append(root.item)
if root.left is not None:
stack.append(root.left)
if root.right is not None:
stack.append(root.right)
print output
return output[::-1]
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
output.append(root.item)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return output