2

I'm trying to implement a Binary Tree, and for ease of debugging, I want to be able to print the tree so it actually looks like a tree. For example:

              50
      42              71
  31      45      60      98
6    11 43  49  55

Or something similar. (The tree is always guaranteed to be complete.) I just need an algorithm or pseudocode to get me started. I just have no idea how implement something like this. Thanks for you help.

thePurpleMonkey
  • 778
  • 2
  • 13
  • 16

2 Answers2

-1

What you have in the question is not exactly a Binary tree. A binary tree at each level has to have the left node smaller than the root and the right node greater that the root.

It can be best implemented with recursion.

Try this link for sample code and explanation.

Ric
  • 1,074
  • 1
  • 7
  • 12
  • Whoops! I knew that. I was just making up numbers for the illustration. I fixed it. I don't think the code in the link you gave me applies to my problem. Apparently nobody wants to do these things with Binary Trees. :/ – thePurpleMonkey May 16 '13 at 20:55
  • Are you not interested in storing the data as a tree, do you just want to print it like a tree ? – Ric May 16 '13 at 21:02
  • The data _is_ stored as a tree, I just can't figure out how to print it like a tree. – thePurpleMonkey May 16 '13 at 21:03
-2

I'll try and start this off: (Took the liberty of using Python 2.x rather than pseudo code).

# Doesn't work yet.
# Assumes two characters ('42', '06' etc) per string representation of number.
# If not, alter the formatting %02d as appropriate.
global line_length
line_length=80
def pad(number_of_nodes):
        global line_length
        return "_"*(line_length/number_of_nodes)

def printlevel(nodes):
        global line_length
        padstring=pad(len(nodes))
        stringnodes=[ "%02d"%(n) for n in nodes ]
        leader="_"* abs( (line_length/2) - len(padstring) )
        print leader, padstring.join(stringnodes)


for level in [  [50],
                [42,71],
                [31,45,60,98],
                [6,11,43,49,55]
        ]:
        printlevel(level)

Since (I believe) the question is more one of formatting than actually visiting tree nodes...I have just flattened out the tree to a list of lists.. This actually doesn't work, but I think it can be re-arranged to get it working....

monojohnny
  • 5,894
  • 16
  • 59
  • 83
  • Does this question have anything to do with Python? I thought it was a Java question. – gparyani May 16 '13 at 23:15
  • 1
    The questioner asked for pseudo-code to illustrate what needs to be done. I used Python instead of pseudo-code. – monojohnny May 17 '13 at 13:17
  • Actually there is already a pretty decent Java implementation of this on stackoverflow : http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram – monojohnny May 17 '13 at 13:18