Inorder traversal is a depth-first traversal method where we visit:
Left β Root β Right
1
/ \
2 3
/ \
4 5
β€ Inorder Traversal Output: 4 2 5 1 3
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(root):
if root:
inorder(root.left) # Left
print(root.val, end=" ") # Root
inorder(root.right) # Right
π For Binary Search Trees (BSTs): Inorder traversal gives the nodes in sorted order! Itβs one of the most important uses of inorder.
When recursion depth is a concern, we can use a stack to simulate inorder traversal:
def inorder_iterative(root):
stack = []
current = root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
print(current.val, end=" ")
current = current.right
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!