[Tutor] Binary Tree Printing Woes

Chimp tuskerduster@yahoo.com
Thu Jun 5 14:13:02 2003


Avast there, Pyrates!

I'm tinkering with Tree structures by following the salient advice from
"How To Think Like A Nerd, eh, Computer Scientist" 
(http://www.ibiblio.org/obp/thinkCSpy/chap20.htm), but printing the tree
in post- and preorder gives me some trouble by slapping a "None" to the
end. It works beautifully in the python shell, just not when I run the
app in my term. 

Could anyone give me a hand?

Anyway, here's the result of running my code, and the scribble below that holds
the key to unleash the horrors:

$ python tree-app.py

Printing  A: 1 2 3			# <--- Tadaaa!  
PreOrder  A: 2 1 3 None     # <--- Arrgh!
PostOrder A: 1 3 2 None	    # <--- Noooo!

---------------------
#! /usr/bin/env python
class Tree:
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.left  = left
        self.right = right

    def __str__(self):
        return str(self.data)

    def print_tree(self, tree):
        if tree is None: return 0
        self.print_tree(tree.left)
        print tree.data,
        self.print_tree(tree.right)

    def print_postorder(self, tree):
        if tree is None: return 0
        self.print_postorder(tree.left)
        self.print_postorder(tree.right)
        print tree.data,

    def print_preorder(self, tree):
        if tree is None: return 0
        print tree.data,
        self.print_preorder(tree.left)
        self.print_preorder(tree.right)

    def build123(self):
        root  = Tree(2)
        left   = Tree(1)
        right  = Tree(3)
        root.left = left
        root.right = right
        return root

if __name__ == '__main__':

    t = Tree()
    a = t.build123()

	print
    print "Printing  A:", t.print_tree(a)
    print "PreOrder  A:", t.print_preorder(a)
    print "PostOrder A:", t.print_postorder(a)

Bizarre, innit?

Oh, and while we're at it: how do you find the parent of a given node? I
need that to find siblings and delete and mess around with the tree in
general. Any hint would be much appreciated and would really help me to
wrap my head around recursion to boot!


-- Chimp
-- 
                            o      _     _         _
------- __o       __o      /\_   _ \\o  (_)\__/o  (_)        -o)
----- _`\<,_    _`\<,_    _>(_) (_)/<_    \_| \   _|/' \/     /\\
---- (_)/ (_)  (_)/ (_)  (_)        (_)   (_)    (_)'  _\o_  _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind