Practical Examples
Tree Traversal: Binary Search Tree
Recursive Approach
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def recursive_inorder(root):
result = []
def traverse(node):
if node:
traverse(node.left)
result.append(node.val)
traverse(node.right)
traverse(root)
return result
Iterative Conversion
def iterative_inorder(root):
result = []
stack = []
current = root
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.val)
current = current.right
return result
Recursion Conversion Flowchart
graph TD
A[Recursive Method] --> B{Identify Recursive Pattern}
B --> C[Create Explicit Stack]
C --> D[Simulate Recursive Calls]
D --> E[Manage State Manually]
Depth-First Search: Graph Traversal
Recursive DFS
def recursive_dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
recursive_dfs(graph, neighbor, visited)
return visited
Iterative DFS
def iterative_dfs(graph, start):
visited = set()
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(neighbor for neighbor in graph[vertex]
if neighbor not in visited)
return visited
Conversion Strategy Comparison
Strategy |
Memory |
Performance |
Complexity |
Recursive |
High |
Lower |
Simpler Code |
Iterative |
Low |
Higher |
More Complex |
Advanced Example: Merge Sort
Recursive Implementation
def recursive_merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = recursive_merge_sort(arr[:mid])
right = recursive_merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
Iterative Merge Sort
def iterative_merge_sort(arr):
width = 1
n = len(arr)
while width < n:
for i in range(0, n, 2*width):
left = arr[i:i+width]
right = arr[i+width:i+2*width]
arr[i:i+2*width] = merge(left, right)
width *= 2
return arr
At LabEx, we recommend:
- Use recursion for clarity and readability
- Convert to iteration for performance-critical sections
- Profile and benchmark your specific use case