Reputation: 248
I have a binary tree with 7 elements which currently looks like this:
1 5 2 7 6 4 3
I am trying to traverse it in postorder and relable the elements as I go, so that it looks like this:
7 3 6 1 2 4 5
using the following function, which is part of my Tree
class:
def relable(self, h): if self.root is not None: self._relable(self.root, h) def _relable(self, node, h): if node is not None: self._relable(node.l, h-2) self._relable(node.r, h-1) node = Node(h)
The rest of my Tree
class is more or less the same as the one here.
I populated the tree by add
ing the numbers 1-7 in a loop.
However, when I call tree.relable(7)
, and then print the tree, the tree is the same.
I'm guessing this has something to do with how Python passes arguments (I'm a C++ programmer) but I don't know how to fix this.
The entirety of my code can be fount here.
Upvotes: 1
Views: 1246
Reputation: 36033
node = Node(h)
is just assigning a local variable, it doesn't have any effect on the node
parameter that was passed to the function. You need to actually modify the node, i.e. node.v = h
.
Upvotes: 2