1

I have a binary search tree data structure class that holds nodes which are objects in the side the class that acts like a binary search tree.

The class is too long to post here, but basically this is how it works. If I want to print the top value of the bst, I would say

print (self._root)

If I wanted to move to the left side of the tree (same with to go to the right, just put right instead of left) , I would say

print (self._root._left)

I hope this is enough so you can help me with my problem

So onto my problem, if I have a bst like:

      6
     / \
    3   8
   / \   \
  1  4   10

I want to be able to print out:

6

3
8

1
4
10

I have written a recursive traverse function:

def traverse(self):

        a = []
        self._traverse_aux(self._root, a)   
        return a

def _traverse_aux(self, node, a):

        if node is not None:
            self._traverse_aux(node._left, a)
            a.append(node._value)
            self._traverse_aux(node._right, a)
        return

How ever, this prints the values in a single array:

[1, 3, 4, 6, 8, 10]

How can I get it to print the way I want above?

l00kitsjake
  • 955
  • 3
  • 11
  • 24
  • possible duplicate of [Printing BFS (Binary Tree) in Level Order with \_specific formatting\_](http://stackoverflow.com/questions/1894846/printing-bfs-binary-tree-in-level-order-with-specific-formatting) – alternate direction Mar 19 '14 at 14:10

1 Answers1

0

Optimally, you're going to want to answer this recursively. This type of traversal in particular is called Breadth-First. Here are some notes on traversal of binary search trees which might be useful to you, although they are in java.

Here is also a very similar (possibly duplicate) question, although as opposed to solving it recursively a solution is given using loops.

alternate direction
  • 622
  • 1
  • 8
  • 21