如何填充二叉搜索树?
我正在尝试从以下类创建一个二叉搜索树:
class Tree(object):
def __init__(self):
self.data = None
self.left = None
self.right = None
这段代码应该能对一个列表进行处理,把它一分为二,然后递归地处理这两个部分。然而,我发现左右两边的节点都是同一个。
def populatetree(words):#not working
middle = len(words)//2
root = Tree()
root.data = wordlist[middle][0]
if len(words) > 3:
root.left = populatetree(words[:len(words)//2])
root.right = populatetree(words[len(words)//2+1:])
else:
if middle!=0:
root.left = Tree()
root.left.data = words[0]
if(len(words)==3):
root.right = Tree()
root.right.data = words[2]
return root
示例输入:
['2', 'a', 'add', 'an', 'be', 'convert', 'integer', 'is', 'print', 'result', 'set', 'thank', 'the', 'to', 'variable', 'x1', 'y2', 'yes', 'you']'
示例输出:
['result']
['be', 'be']
['add', 'add', 'add', 'add']
['a', '2', 'a', '2', 'a', '2', 'a', '2']
['2', 'convert', 'set', 'x1']
输出的格式是金字塔形的,也就是说,be
和 be
都属于 result
,第一个 add
和第二个 add
属于第一个 be
,接下来的两个 adds
属于另一个 be
,依此类推。我检查了实际的数据,发现 tree.left.data
和 tree.right.data
确实都是 be
和 be
。这让我很困惑,因为右边的子树根本不应该看到 be
,因为我传给它的是列表的右半部分。
你觉得我需要做些什么不同的事情,才能正确填充这个列表呢?
1 个回答
1
看起来Tree.data是从一个叫“wordlist”的东西中获取的,但在你提供的示例代码里并没有定义这个“wordlist”,而且它也不是函数populatetree的参数。也许“wordlist”就是最初的列表?