Last active
June 27, 2021 08:09
-
-
Save anchitarnav/79f6ceff58ea1ff173ff7cceb01f2f11 to your computer and use it in GitHub Desktop.
Tree Traversals iterative
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
# Definition for a binary tree node. | |
class TreeNode: | |
def __init__(self, x): | |
self.val = x | |
self.left = None | |
self.right = None | |
class Stack(list): | |
def push(self, node): | |
self.append(node) | |
def peek(self): | |
return self[-1] | |
def iterativeDfsPreOrder(root): | |
stack = Stack() | |
stack.push(root) | |
# Pre Order Traversal | |
# Same as BFS, just with a stack instead of a Queue | |
print ("\n\nPreOrder Root -> Left -> Right") | |
while stack: | |
current = stack.pop() | |
print(current.val, end=' -> ') | |
# In Reverse order | |
if current.right: | |
stack.push(current.right) | |
if current.left: | |
stack.push(current.left) | |
def iterativeDfsPostOrder(root): | |
# Post Order Traversal | |
print("\n\nPostOrder Left -> Right -> Root") | |
stack = Stack() | |
current = root | |
while True: | |
while current is not None: | |
if current.right: | |
stack.push(current.right) | |
stack.push(current) | |
current = current.left | |
# current == None here in all cases | |
current = stack.pop() | |
if stack and stack.peek() == current.right: | |
right_child = stack.pop() | |
stack.push(current) | |
current = right_child | |
else: | |
print(current.val, end = " -> ") | |
# This ensures that the next interation picks up a new element from stack | |
current = None | |
if not stack and current is None: | |
break | |
def iterativeDfsInOrder(root): | |
# In Order Traversal | |
print("\n\nInOrder Left -> Root -> Right") | |
stack = Stack() | |
current = root | |
while True: | |
# print([x.val for x in stack]) | |
while current is not None: | |
if current.right: | |
stack.push(current.right) | |
stack.push(current) | |
current = current.left | |
# print([x.val for x in stack]) | |
# current == None here in all cases | |
current = stack.pop() | |
print(current.val, end=" -> ") | |
if stack and stack.peek() == current.right: | |
right_child = stack.pop() | |
current = right_child | |
else: | |
# This ensures that the next interation picks up a new element from stack | |
current = None | |
if not stack and current is None: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment