【发布时间】:2017-05-29 00:05:37
【问题描述】:
我需要实现一个二叉搜索树类作为作业,但我很难实现插入功能。我已经通过谷歌看了很多,以找到一些解决方案或可能性,但他们都没有使用键和值(主要是值),或者如果他们也使用了键,他们有很多单独的功能,我是我认为不允许这样做。
所以预建就是:
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def insert(self, key, value):
pass
def remove(self, key):
pass
def find(self, key):
pass
现在的问题是,如果我想检查例如该值是小于还是大于当前节点以将其放在右侧或左侧,我会收到诸如“root is not defined”或“root.right”之类的错误" 没有这样的属性等... 我想这是有道理的,因为 self.root 被声明为 None。
但是我现在如何真正修复它以使插入功能正常工作?
我对这个任务有点困惑,因为它使用键+值,所以我需要插入绑定到特定键的值,如果键已经存在,覆盖它的值。
【问题讨论】:
-
self.root是干什么用的? -
说实话,我自己都不认识……根可能是树的第一个。
-
哦,我想我明白了。根只是一个节点。让您的插入函数检查 root 是否为
None,如果是,则为其分配一个新节点
标签: python insert key binary-search-tree