简体   繁体   中英

Inserting a node in Binary search tree in python

i know the basic working code for inserting Node in BST.
But i expected this function to add a Node at the right end of BST (because its value is the maximum in that tree), but it doesn't work and i wanna know the reason. Tried debugging but still not clear.
def putValueInBST(root, val):  # assuming the val = 7 which is max of all the existing node values in BST
    if root is None:
        root = Node(val)
    elif val > root.data:
        putValueInBST(root.right, val)
    else:
        putValueInBST(root.left, val)
This works as expected...
def put_val_manually(r, val):
    r.right.right = Node(val)
My doubt is, aren't both of the above functions kinda similar, since they are adding the Node in the end of the BST ?

(of course in the put_val_manually() function, i am doing it directly.)

The full code is here: https://i.ibb.co/yf2YTYy/code.png

Try to return the node

def putValueInBST(root, val):  # assuming the val = 7 which is max of all the existing node values in BST
    if root is None:
        return Node(val)
    elif val > root.data:
        root.right=putValueInBST(root.right, val)
    else:
        root.left=putValueInBST(root.left, val)

root=putValueInBST(root,val)

This code works

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