[Tutor] Binary Tree Printing Woes
Chimp
tutor@python.org
Fri Jun 6 04:47:02 2003
* Alan Gauld <alan.gauld@blueyonder.co.uk> [030605 22:19]:
> > print "Printing A:", t.print_tree(a)
> > print "PreOrder A:", t.print_preorder(a)
> > print "PostOrder A:", t.print_postorder(a)
>
> Here you print the string then the return value from
> the print functions. But the print functiond=s do their
> own printing and don't retirn anything. When a function
> doesn't explicitly return anything Python provides a
> default of None.
>
> Thus:
>
> >>> def f(): pass
> ...
> >>> print f()
> None
> >>>
That was a great explanation and a very neat example! But how come the
print_tree() function - which ALSO returns None works just dandy?! I
tried - just for the sheer heck of it - to change change the "return
None" to "pass" - and even "break" when I got *really* desperate. "Pass"
had the exact same effect. I won't even tell you what "break" did. :o)
def print_tree(self, node):
if node is None:
pass
else:
self.print_tree(node.left)
print node.data,
self.print_tree(node.right)
def print_postorder(self, node):
if node is None:
pass
else:
self.print_postorder(node.left)
self.print_postorder(node.right)
print node.data,
> You are seeing the None coming back from the functions.
But how do I rewrite the function so make the "print" ignore it? I tried
this, but alas, it had the same effect:
def print_postorder(self, node):
if node is None: return None
self.print_postorder(node.left)
self.print_postorder(node.right)
if node.data: print node.data, <---
>> Bizarre, innit?
> Not really :-)
Actually, now it's getting downright SPOOKY! ;o)
>> Oh, and while we're at it: how do you find the parent of a given node?
> You need to store a reference in each child(as Tkinter does
> with its widgets) or alternatively write a function that
> searches the tree for a node which has your node as a child!
> I recommend storing the parent as an attribute of the Node!
DAMN, I *knew* it. Freaky how none of the tuts out there mentioned
anything about either way, but now that you mention it it just seems too
logical. DOH (*slaps forehead*). The first should be easy: I did
actually manage to get a function working that returns the children and
I have 2 sexy search functions to boot. But I like your parent-reference
idea mucho better.
Thanks for taking the time, Alan! I'm gonna post my entire tree library
for the other newbies once I've solved the printing-problemo and added
3-4 other handy functions which will be possible now that I have a
chance at the get_parent() thingy.
See ya'!
-- Chimp
--
o _ _ _
------- __o __o /\_ _ \\o (_)\__/o (_) -o)
----- _`\<,_ _`\<,_ _>(_) (_)/<_ \_| \ _|/' \/ /\\
---- (_)/ (_) (_)/ (_) (_) (_) (_) (_)' _\o_ _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind