【发布时间】:2022-01-13 07:22:14
【问题描述】:
我是数据结构的初学者,我正在使用 Python 从列表中创建决策二叉树,列表的元素应该在叶子中。列表的长度始终是一对数字。
我创建了一个二叉树的数据结构:
class BinaryTree:
def __init__(self, value):
self.value= value
self.left = None
self.right = None
def insert_left(self, value):
if self.left == None:
self.left = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.left = self.left
self.left= new_node
def insert_right(self, value):
if self.right== None:
self.right= BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.right= self.right
self.right= new_node
def get_value(self):
return self.value
def get_left(self):
return self.left
def get_right(self):
return self.right
我创建了一个递归函数来实现一棵树:
def cons_tree(leaflist):
size = len(leaflist)
tag = int(math.log(size)/math.log(2))
return cons_tree_sub(tag, leaflist)
def cons_tree_sub(tag, leaflist):
size = len(leaflist)
abd = BinaryTree(tag)
if size < 3:
abd.insert_left(leaflist[0])
abd.insert_right(leaflist[1])
else :
mid= size//2
subList1= leaflist[:mid]
subList2= leaflist[mid:]
#the code in java is :
#return new Node(tag,cons_tree_sub(tag-1,subList1),cons_tree_sub(tag-1,subList2));
abd.insert_left(cons_tree_sub(tag-1, subList1))
abd.insert_right(cons_tree_sub(tag-1, subList2))
return abd
def display(T):
if T != None:
print (T.get_value(),display(T.get_left()),display(T.get_right()))
abd = cons_tree([False, True, True, False, False, True, False, False])
display(abd)
当我执行程序时,我得到了这个结果:
_________________________3__________________________
/ \
<__main__.BinaryTree object at 0x000002B3F25E8F70> <__main__.BinaryTree object at 0x000002B3F25E87C0>
我知道当我在左侧或右侧插入时我插入的是一个树而不是一个值,我如何才能在递归函数中实现所有树的子级
我尝试为 return 函数做 get_value() 因为它返回一棵树:
abd.insert_left(cons_tree_sub(tag-1, subList1).get_value())
abd.insert_right(cons_tree_sub(tag-1, subList2).get_value())
但我有一个不完整树的结果:
3
/ \
2 2
我想要的结果是:
__________3__________
/ \
____2____ ____2_____
/ \ / \
__1__ _1__ __1__ __1__
/ \ / \ / \ / \
False True True False False True False False
【问题讨论】:
-
您的问题不包括
display方法。另外:您的输入大小总是2的幂吗?或者换句话说,你总是在创建一个完美的二叉树吗? -
@trincot 我没有放它,因为我不想在我的问题中放很多不必要的代码。我的问题是关注
cons_tree_sub功能 -
请查看我的其他问题...
-
一个小问题,但最好避免使用诸如
list之类的关键字作为变量名。当您最终调用 in buildlist函数而不是您的变量时,它可能会导致混淆。它还使您的代码更难阅读 -
我认为这不仅仅是一个小问题。它不仅非常令人困惑,而且 python 绑定是动态的,而不是作用域的。这意味着,如果您的变量之一被命名为
list,并且您调用了一个本身调用list的函数,那么所有的地狱都会崩溃。请不要调用任何变量list。
标签: python data-structures binary-tree