Postorder traversal is a depth-first traversal method where nodes are visited in the order:
Left → Right → Root
1
/ \
2 3
/ \
4 5
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def postorder(root):
if root:
postorder(root.left) # Left
postorder(root.right) # Right
print(root.val, end=" ") # Root
📌 File system deletion: Postorder is useful when you need to delete a directory — delete files (children) first, then the directory (parent).
Postorder can also be done without recursion using two stacks:
def postorder_iterative(root):
if root is None:
return
s1, s2 = [], []
s1.append(root)
while s1:
node = s1.pop()
s2.append(node)
if node.left:
s1.append(node.left)
if node.right:
s1.append(node.right)
while s2:
print(s2.pop().val, end=" ")
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!