I'm trying to implement a recursive algorithm in Python to traverse a binary tree and print out all the nodes in order. However, when I run my code, I'm getting a "maximum recursion depth exceeded" error.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
if not root:
return []
result = []
result += inorder_traversal(root.left)
result.append(root.val)
result += inorder_traversal(root.right)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(inorder_traversal(root))