Reputation: 75
I am trying to traverse a heap, and write the traversal to a file but I am failing miserably.
I keep getting an issue with the maximum traversal depth that spams my terminal when all I want is for the node to be printed out in the file.
Upvotes: 0
Views: 21
Reputation: 122090
I think your code should look more like this:
def inorder(self, file):
if self._left is not None:
file.write(str(self) + ' ')
self._left.inorder(file)
file.write(str(self) + ' ')
if self._right is not None:
file.write(str(self) + ' ')
self._right.inorder(file)
Note that:
file
to write to is an argument, passed to the recursive calls, not open
ed each time;None
by identity not equality; andself._left
and self._right
are instances of the same class as self
(as you've provided so little of the class, it's hard to be sure, but self.inorder(self._left)
makes no sense). When you call this, on some instance instance
of your class, it would look like:
with open(...) as f:
instance.inorder(f)
Upvotes: 1