【问题标题】:Failed to insert value into Binary Search Tree无法将值插入二叉搜索树
【发布时间】:2020-03-16 12:57:53
【问题描述】:

我在 BST 的插入功能上遇到了一些问题。

运行这些代码后似乎没有输出返回;但是,我无法成功地将值插入树中。

更准确地说,当我使用 Spyder 进行检查时,root 的值是NoneType object of bulitins module。结果,我很确定我未能将值插入到树中。而且我怀疑这是由于根的NoneType,但即使我尝试在运行代码之前给根一个值root = TreeNode(3) 然后Solution().insert(root, 5)。我不确定如何解决这个问题。

请看下面的代码。

class TreeNode():
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution():    

    def insert(self, root, val):

        if root is None:
            root = TreeNode(val)
            return root
        else:
            if val <= root.val:
                if root.left:
                    root.left = self.insert(root.left, val)
            else:
                if root.right:
                    root.right = self.insert(root.right, val)
                return root


root = None
Solution().insert(root, 5)

任何建议将不胜感激!

【问题讨论】:

    标签: python python-3.x binary-search-tree nonetype insertion


    【解决方案1】:

    在递归调用的条件以及仅在树的右侧不是树的左侧,这就是为什么它不能按照您的期望工作:

    def insert(self, root, val):
    
        if root is None:
            root = TreeNode(val)
            return root
        else:
            if val <= root.val:
                root.left = self.insert(root.left, val)
            else:
                root.right = self.insert(root.right, val)
            return root
    

    这是工作代码的链接:link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2013-05-06
      • 1970-01-01
      • 2012-04-24
      相关资源
      最近更新 更多