-1

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))

pvpb0t
  • 33
  • 6
  • 3
    I cannot reproduce this with the code you provided. Please provide the code with which you actually get the error. – trincot Apr 29 '23 at 18:41
  • Are you sure you aren't creating a cycle in your tree on accident, assuming this example is a mockup? – B Remmelzwaal Apr 29 '23 at 18:54

1 Answers1

-3

Set recursion limit.

import sys
sys.setrecursionlimit(n) # default is 1000, you probably want something like 3000
SimonUnderwood
  • 469
  • 3
  • 12