【问题标题】:Why this python code for insertion into binary search tree not working?为什么这个插入二叉搜索树的python代码不起作用?
【发布时间】:2020-04-21 17:03:07
【问题描述】:

为什么这个插入二叉搜索树的代码不起作用?

  class BinaryTreeNode:
        def __init__(self,key):
            self.key=key
            self.left=None
            self.right=None

    def insert(root,data):
        if root is None:
            root=BinaryTreeNode(data)
        else:
            if data>root.key:       
                insert(root.right,data)
            else:
                insert(root.left,data)y

【问题讨论】:

  • 看起来else: 块中的代码不应该在else 块内
  • 欢迎来到 SO!请澄清究竟是什么不起作用。
  • 你永远不会给root.leftroot.right分配任何东西。
  • 太多的拼写错误:删除最后一行的y,第二个defies not properly indented, insert`需要有一个self参数,如果它是一个方法并且你从不分配左右。
  • @MarkMeyer 如果说 root.right 是 None 那么它将被分配递归调用中的节点对吗?

标签: python data-structures binary-search-tree


【解决方案1】:

代码的逻辑看起来非常好,但我有一个担心。 在这段代码中,它是否返回什么?

  class BinaryTreeNode:
    def __init__(self,key):
        self.key=key
        self.left=None
        self.right=None

def insert(root,data):
    if root is None:
        root=BinaryTreeNode(data)
    else:
        if data>root.key:       
            insert(root.right,data)
        else:
            insert(root.left,data)
    return

我在你的insert方法中加了一个return,也许现在可以运行了。由于缺少return,你的方法会一直调用自己,但是如果不return,堆栈就不会关闭,导致你的程序永远卡住。

我也创建了一个插入方法,也许你可以检查并测试你是否错过了某个地方。

def insert(self, val):
    treeNode = Node(val)
    placed = 0
    tmp = self.root
    if not self.root:
        self.root = treeNode
    else:
        while(not placed):
            if val<tmp.info:
                if not tmp.left:
                    tmp.left = treeNode
                    placed = 1
                else:
                    tmp = tmp.left
            else:
                if not tmp.right:
                    tmp.right = treeNode
                    placed = 1
                else:
                    tmp = tmp.right
    return 

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多