In Inorder traversal, we visit nodes in this order:
When applied to a Binary Search Tree, Inorder traversal always gives nodes in ascending sorted order.
🌳 Example Binary Search Tree:
40
/ \
20 60
/ \ / \
10 30 50 70
🔁 Inorder Traversal Step-by-Step:
- Traverse left subtree →
- Visit root →
- Traverse right subtree
🔢 Inorder Traversal Output:
10 → 20 → 30 → 40 → 50 → 60 → 70
This is sorted order!
📌 Python Code:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(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)
# Inorder Traversal
inorder(root)
📌 Key Point:
✅ Inorder traversal in BST = Sorted Output
No comments:
Post a Comment