Practical Code Examples
Tree Traversal: Recursive vs Iterative
Recursive Approach
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_recursive(root):
result = []
def traverse(node):
if not node:
return
traverse(node.left)
result.append(node.val)
traverse(node.right)
traverse(root)
return result
Iterative Approach
def inorder_iterative(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
Depth-First Search: Recursive vs Iterative
graph TD
A[Start Node] --> B[Recursive DFS]
A --> C[Iterative DFS]
B --> D[Recursive Stack]
C --> E[Explicit Stack]
Graph Traversal Example
Recursive Graph Traversal
def dfs_recursive(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs_recursive(graph, neighbor, visited)
return visited
Iterative Graph Traversal
def dfs_iterative(graph, start_node):
visited = set()
stack = [start_node]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
stack.extend(
neighbor for neighbor in graph[node]
if neighbor not in visited
)
return visited
Complexity Comparison
Algorithm |
Recursive |
Iterative |
Space Complexity |
O(n) |
O(1) |
Time Complexity |
O(n) |
O(n) |
Stack Usage |
System Stack |
Manual Stack |
Readability |
High |
Medium |
Advanced Recursion to Loop Conversion
Merge Sort Example
def merge_sort_recursive(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_recursive(arr[:mid])
right = merge_sort_recursive(arr[mid:])
return merge(left, right)
def merge_sort_iterative(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
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
Learning with LabEx
At LabEx, we recommend practicing these conversion techniques to develop a deeper understanding of algorithmic problem-solving strategies.
Key Takeaways
- Most recursive algorithms can be converted to iterative solutions
- Iterative approaches often have better memory efficiency
- Choose the approach based on readability and performance requirements
- Practice is key to mastering recursion and iteration