Search code examples
pythonpython-3.xfile-ioheaptraversal

Writing traversals to a file in python3.x issue


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.


Solution

  • 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:

    1. The file to write to is an argument, passed to the recursive calls, not opened each time;
    2. Testing for None by identity not equality; and
    3. I am assuming that you have a tree structure where self._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)