[Tutor] Tree that doesn't grow
Karl Pflästerer
sigurd at 12move.de
Mon Mar 8 15:09:04 EST 2004
On 4 Mar 2004, Md. Zahar Othman <- zahar at upsi.edu.my wrote:
> I'm a newbie trying to convert my old Pascal tree program - pointer
> implementation to python OOP
And here is the problem: python has call by value semantics whereas
Pascal has IIRC call by reference or call by value (you can choose).
> Why the method does not work ?
Because of the different semantic.
> =============================
> class binary_tree:
> def __init__(self):
> self.tree=None
> def insert (self,key):
> if self.tree:
> self._insert(self.tree,key)
> else:
> self.tree = node(key)
> def _insert (self,tree,key):
> if tree==None:
> tree = node(key)
In Pascal this could be a pointer or a reference to an address but in
Python this won't work that way.
You could change your code a bit:
class binary_tree:
def __init__(self):
self.tree=None
def insert (self,key):
if self.tree:
self._insert(self.tree,key)
else:
self.tree = node(key)
def _insert (self,tree,key):
if key < tree.key:
if tree.left:
self._insert(tree.left,key)
else: tree.left = node(key)
elif key > tree.key:
if tree.right:
self._insert(tree.right,key)
else: tree.right = node(key)
>>> p = binary_tree()
>>> p.insert(10)
>>> p.insert(11)
>>> p.insert(9)
>>> p.insert(12)
>>> p.tree.key
10
>>> p.tree.left.key
9
>>> p.tree.right.key
11
>>> p.tree.right.right.key
12
>>>
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list