#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Posts
    2
    Rep Power
    0

    Help on implementing a binary search tree please


    Hi everyone!

    I have a homework assignment requiring the implementation of a binary search tree.

    I have a problem with the "putta" method, which is supposed to add new nodes to the tree. It adds one node and then just says that the data of all new nodes are identical to the single existing nodes data.

    I have low understanding of the "return" parameter, but I believe it has something to do with it.

    The data I am trying to add is three letter words.

    Please help me!!!


    Code:
    def putta(p,newvalue):
        ny = node
        ny.value = newvalue
        ny.left = None
        ny.right = None
        if p is None:
            p = ny
            return p
        if newvalue<p.value:
            p.left = putta(p.left,newvalue)
        elif newvalue>p.value:
            p.right = putta(p.right,newvalue)
        else:
            print "Ordet: ", newvalue,", fanns redan."
        return p
    
    class bintree:
        root = None
    
        def put(self, newvalue):
            self.root = putta(self.root,newvalue)
    
    class node:
        value = None
        left = None
        right = None
    
    svenska=bintree()
    svenska.put("gur")
    svenska.put("aaa")
  2. #2
  3. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Norcross, GA (again)
    Posts
    1,804
    Rep Power
    1569
    It's actually a simple typo that's at fault; you forgot the parentheses in the declaration of ny:
    Code:
    ny = node()
    If you make this change, and add the following test lines after the two test insertions, it should demonstrate the tree behavior quite nicely.
    Code:
    print(svenska.root.value)
    print(svenska.root.left.value)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Posts
    2
    Rep Power
    0

    Million thanks!


    Thank you so much Schol-R-LEA! You really saved the day, now everything works fine!

    Today you brought some peace into this world!!!
    Happy Holidays /Cooper

IMN logo majestic logo threadwatch logo seochat tools logo