0

I know this has been asked before, but I really don't get what I'm doing wrong. I'm trying to traverse a BST in pre-order fashion. The function below is member of a BST class, which contains self.root. Please help.

def pre_print(self, node=None):
 if not node:
 node = self.root
 print(node.data)
 self.pre_print(node.left)
 self.pre_print(node.right)

It keeps printing 2 or 3 values then I get this error

RecursionError: maximum recursion depth exceeded while calling a Python object
 
asked Oct 24, 2020 at 17:44
1
  • It's really hard to answer without seeing your class. But guessing, pre_print should be a method on nodes. Then you call it on each child: self.left.pre_print(). Test first that the left or right node is not None. Commented Oct 24, 2020 at 17:59

2 Answers 2

2

Since you need some initialization if no node is provided, just add a simple check

def pre_print(self, node=None):
 if not node:
 node = self.root
 print(node.data)
 if node.left:
 self.pre_print(node.left)
 if node.right:
 self.pre_print(node.right)
answered Oct 24, 2020 at 17:45
Sign up to request clarification or add additional context in comments.

1 Comment

The function does nothing if I do that, That line is there to use the root node as a starting point if no other node is provided as an argument.
2

When the recursion arrives at a point in which self==(one of the leafs), I'm assuming its node.left and node.right are ==None, at which point, the next recursion enters the if statement since its node arg is ==None and then sets the ```node==(the self of the leaf node that called this function/method).root).

Which results in this function call being somewhat the similar to the one that was run before it. Resulting in a infinite recursion.

A simple check before entering your method can evade this problem.

def pre_print(self, node=None):
 if not node:
 node = self.root
 print(node.data)
 if node.left : self.pre_print(node.left)
 if node.right: self.pre_print(node.right)
answered Oct 24, 2020 at 18:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.