【发布时间】:2021-01-17 08:13:01
【问题描述】:
我知道以前有人问过这类问题,我并不是盲目地问你们这个问题,因为我已经回答了以前的问题,但我完全没有得到它。这是下面的代码:
class Node():
def __init__(self,data):
self.data=data
self.left=None
self.right=None
class BST():
def __init__(self):
self.head=None
def insert(self,data):
if self.head is None:
self.head=Node(data)
if self.head:
if data<self.head.data:
if self.head.left is None:
self.head.left=Node(data)
else:
self.head.left.insert(data)
if data>self.head.data:
if self.head.right is None:
self.head.right=Node(data)
else:
self.head.right.insert(data) #Actual error point
l1=BST()
l1.insert(2)
l1.insert(4)
l1.insert(6) #Getting the error while inserting this
我知道我要么需要将 insert 方法放在 Node 类中,要么将 Node 类属性继承到 BST 类中,但是我很难实现这两种解决方案,请你们走我通过这两种解决方案,用书面代码的解释对我真的很有帮助。
你可能已经厌倦了看到这些问题,你们都是这里的专家,你知道这对于初学者来说有多难,尤其是我不想从不清楚的概念开始。
【问题讨论】:
-
stackoverflow 不是一个教程网站,所以在我看来你问的不是主题。
-
@martineau 你至少能给我一个解决我的错误的方法吗?
-
我不会给你一个完整的解决方案,但你可能会发现了解
left和right应该是子树而不是独立的节点。所以你根本不需要class Node- 只需将data放在class BST中。
标签: python python-3.x data-structures binary-search-tree object-reference