Mental Model
Visit the left side first, then the middle, then the right side in order.
Analogy: Imagine reading a book where you first look at the left page, then the center page, then the right page in order.
1 / \ 2 3 / 4 ā start at root (1)
1 / \ 2 3 / 4 ā start at root (1)
1 -> [curr->2] -> 3 2 -> [curr->4] 4 3
1 -> 2 -> [curr->4] -> 3 4
Visited: 4 1 -> 2 -> 3
Visited: 4, 2 1 -> 3
Visited: 4, 2, 1 3
Visited: 4, 2, 1, 3
4 -> 2 -> 1 -> 3
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_traversal(root): result = [] def helper(node): if node is None: return helper(node.left) # visit left subtree first result.append(node.val) # then visit root helper(node.right) # finally visit right subtree helper(root) return result # Build tree from dry_run input root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) output = inorder_traversal(root) print(' -> '.join(map(str, output)))
helper(node.left) # visit left subtree firstresult.append(node.val) # then visit roothelper(node.right) # finally visit right subtreeif node is None: return
if node is None: return
helper(node.left) # visit left subtree firstroot?
2
/ \
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)
print(root.val, end=' ')
inorder(root.right)
root = Node(2)
root.left = Node(1)
root.right = Node(3)
inorder(root)
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(root):
inorder(root.left)
print(root.val, end=' ')
inorder(root.right)
root = Node(1)
inorder(root)
if root is None: return fixes it.
5
/ \
3 8
\ \
4 9
Options:
A) 3 5 4 8 9
B) 4 3 5 9 8
C) 3 4 5 8 9
D) 5 3 4 8 9Pass the test and this pattern moves unknown