Skip to content

Instantly share code, notes, and snippets.

@siavashk
Last active December 1, 2024 22:40
Show Gist options
  • Save siavashk/662f87c8e6def5752cbde446d0a0c09c to your computer and use it in GitHub Desktop.
Save siavashk/662f87c8e6def5752cbde446d0a0c09c to your computer and use it in GitHub Desktop.
DFS Iterative Binary Tree Traversal
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def iterative_pre_order_traversal(root: TreeNode):
stack = [root]
while stack:
node = stack.pop()
# Here we process the node before the left and right children
print(node.val)
# We append the right node first because stack is LIFO
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
def iterative_in_order_traversal(root: TreeNode):
stack = []
node = root
while stack or node:
# Navigate to the left-most node first
while node:
stack.append(node)
node = node.left
node = stack.pop()
# Notice we process the left sub-tree
# before processing the current node and
# moving to the right sub-tree
print(node.val)
node = node.right
def iterative_post_order_traversal(root: TreeNode):
stack = []
last_visited = None
node = root
while stack or node:
# Traverse the left subtree if not visited already
if node:
stack.append(node)
node = node.left
# Traverse the right subtree if not visited already
elif stack[-1].right and stack[-1].right != last_visited:
node = stack[-1].right
else:
# Process the node
print(stack[-1].val)
last_visited = stack.pop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment