In Preorder traversal, we visit nodes in this order:
It is mainly used to copy or clone a binary tree or save its structure.
🌳 Example Binary Search Tree:
40
/ \
20 60
/ \ / \
10 30 50 70
🔁 Preorder Traversal Step-by-Step:
- Visit root →
- Traverse left subtree →
- Traverse right subtree
🔢 Preorder Traversal Output:
40 → 20 → 10 → 30 → 60 → 50 → 70
📌 Python Code:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def preorder(root):
if root:
print(root.val, end=" ")
preorder(root.left)
preorder(root.right)
# 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)
# Preorder Traversal
preorder(root)
📌 Key Point:
✅ Preorder traversal starts with the root first.
No comments:
Post a Comment