someone
someone

Reputation: 15

Binary tree with python

I don't understand where am I making a mistake, the following is the code for creating a tree but it never creates the tree. I think there is some logical mistake in the make_tree function.

    class node:

    def __init__(self, a):
        self.a=a
        self.l=None
        self.r=None


class tree:
    def __init__(self, a,maxd=5):
        self.s=node(a)
        self.maxd=maxd

    def make_tree(self, n,d=0):

        if(self.maxd<d):
            return n
        else:

            n=node(d)
            n.a=d
            self.make_tree( n.l,d+1)
            self.make_tree(n.r,d+1)

            return n

t=tree(2)
t.s=t.make_tree(t.s)
print 'children ', (t.s.r!=None), (t.s.l!=None)

output:

children False False

want a tree like this:

     o
   /   \
  o     o
/  \   / \
o   o  o  o

Upvotes: 0

Views: 222

Answers (1)

Blckknght
Blckknght

Reputation: 104712

I think you're expecting the line:

n=node(d)

to do more than it can do in Python. That line rebinds the local name n, but it doesn't change where the original n value came from in the calling code.

I think you should skip passing n to the make_tree function entirely and simply use its return value instead:

def make_tree(self, d=0):
    if d > self.maxd:
        return None
    n = Node(d)
    n.l = self.make_tree(d+1)
    n.r = self.make_tree(d+1)
    return n

You'd call it with something like:

tree.s = tree.make_tree()

Of course, make_tree could be a regular function rather than a method, since it only uses self to call itself recursively.

Upvotes: 1

Related Questions