簡體   English   中英

在python的二叉搜索樹中插入節點

[英]Inserting a node in Binary search tree in python

我知道在 BST 中插入節點的基本工作代碼。
但是我希望這個函數在 BST 的右端添加一個節點(因為它的值是該樹中的最大值),但它不起作用,我想知道原因。 試過調試但還是不清楚。
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)
這按預期工作......
def put_val_manually(r, val):
    r.right.right = Node(val)
我的疑問是,上述兩個函數是不是有點相似,因為它們在 BST 的末尾添加了 Node ?

(當然在put_val_manually()函數中,我是直接做的。)

完整代碼在這里: https : //i.ibb.co/yf2YTYy/code.png

嘗試返回節點

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)

此代碼有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM