【问题标题】:Inserting a node in Binary search tree in python在python的二叉搜索树中插入一个节点
【发布时间】:2021-10-24 16:42:27
【问题描述】:

我知道在 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 的末尾添加节点? (当然在put_val_manually()函数中,我是直接做的。)

完整代码在这里:https://i.ibb.co/yf2YTYy/code.png

【问题讨论】:

  • root = Node(val):这会更新参数root。这行不通。参数总是在python中按值传递。所以基本上这种说法是没有用的。
  • 感谢@qouify 的回答。我想我将不得不阅读更多关于 python 如何处理函数参数的信息。

标签: python insert binary-search-tree


【解决方案1】:

尝试返回节点

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)

此代码有效

【讨论】:

  • 函数末尾需要return root
  • @Kirushikesh 我知道正确的代码,但我的问题不同:)
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多