In Postorder traversal, the order of visiting nodes is:
This traversal is useful for deleting the tree, as it visits children before the parent node.
🌳 Example Binary Search Tree:
40
/ \
20 60
/ \ / \
10 30 50 70
🔁 Postorder Traversal Step-by-Step:
- Traverse left subtree →
- Traverse right subtree →
- Visit root
🔢 Postorder Traversal Output:
10 → 30 → 20 → 50 → 70 → 60 → 40
📌 Python Code:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val, end=" ")
# Create BST
root = Node(40)
root.left = Node(20)
root.right = Node(60)
root.left.left = Node(10)
root.left.right = Node(30)
root.right.left = Node(50)
root.right.right = Node(70)
# Postorder Traversal
postorder(root)
📌 Key Point:
✅ Postorder traversal is best for deleting or freeing memory (bottom-up approach).
No comments:
Post a Comment