简体   繁体   中英

how to add a node in a binary search tree

I have this 2 function - 1st is creating a node , 2nd is a recursion function that goes through the tree in order to find a placement for a value:

def create_node(number=None):
    return {"Number": number, "Right": None, "Left":None}

def insert(number, pointer):
    pointer_number=pointer["number"]

    if pointer_number is none:
        pointer["number"]=number

    elif number > pointer_number:
        if pointer["right"] is none:
            pointer["right"] = create_node(number)
        else:
            insert(number, pointer["right"])
    else:
        if pointer["left"] is none:
            pointer["left"] = create_node(number)
        else:
            insert (number, pointer["left"]) 

Now I've created the root of the tree:

root = create_node(5)

The problem i face is when i try to add a value to the tree using the insert function. I'm missing something and I don't know how to do it. Please advise ..

So 2 things

  • NoneType is capitalized: None (all if's you do in create_node )
  • Python string comparison is casesensitive, so when you check for pointer["number"] value you are not really checking the one you set in the create_node method, which it's key is "Number" (capital "N"), being the reason it throws KeyError . Same for "right" and "left" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM