Tree Traversals are the ways to visit every node in a binary tree. There are three main orders — and they're all just 3 lines of code! 🌳
💡 Think of it like this: Imagine you're in a building checking every room. Do you check the current floor first, or go straight upstairs? The three traversals differ in WHEN you visit the current node:
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Level-Order Traversal (BFS): Visit level by level using a queue.
Remember: In/Pre/Post refers to when you visit the ROOT. In-order = root in the middle. Pre-order = root first. Post-order = root last.
# 1
# / \
# 2 3
# / \
# 4 5
def inorder(node): # Left → ROOT → Right
if not node: return
inorder(node.left) # Result: 4, 2, 5, 1, 3
print(node.val) # (Gives SORTED order in BST!)
inorder(node.right)
def preorder(node): # ROOT → Left → Right
if not node: return
print(node.val) # Result: 1, 2, 4, 5, 3
preorder(node.left) # (Used to COPY a tree)
preorder(node.right)
def postorder(node): # Left → Right → ROOT
if not node: return
postorder(node.left) # Result: 4, 5, 2, 3, 1
postorder(node.right) # (Used to DELETE a tree)
print(node.val)
inorder(root)
[4, 2, 5, 1, 3]
preorder(root)
[1, 2, 4, 5, 3]
postorder(root)
[4, 5, 2, 3, 1]