[英]Populating a binary search tree?
我正在尝试从以下类创建二进制搜索树:
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
属于可以了,接下来的两个adds
属于其他be
,等等等等。 我已经检查了实际数据,并且tree.left.data
和tree.right.data
实际上都是be
和be
。 这令我感到困惑,因为右子树甚至不应该能够看到be
因为我传给它的右半边list
。
知道我需要做些什么才能正确填充列表吗?
看起来Tree.data是从名为“ wordlist”的东西中获取的,它在您提供的示例代码中未定义,并且不是函数populatetree的参数。 也许单词列表是原始列表?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.