我希望打印出[6,5,10
相反,我只获得10
:
class BST:
arr = []
def __init__(self):
self.height = 0
self.key = 0
self.left = None
self.right = None
def __str__(self):
return str(self.key)
def populate(self):
print("populating")
print(self.key)
if (self.left != None):
BST.arr = BST.arr + [self.left.populate()]
if (self.right != None):
BST.arr = BST.arr + [self.right.populate()]
return self.key
m1 = BST()
m1.key = 10
m2 = BST()
m2.key = 5
m1.left = m2
print(m1.left != None)
m3 = BST()
m3.key = 6
m2.left = m3
res = m1.populate()
print(res)
答案 0 :(得分:1)
这是一个按顺序遍历的函数:
def inOrder(node, order):
if node is not None:
inOrder(node.left, order)
order.append(node.key)
inOrder(node.right, order)
你可以编写一个包装函数,它确实返回一个列表并像这样使用它:
def inOrder(root):
order = []
inOrder(root, order)
return order
编辑:或者您可以使用以下一个函数执行此操作:
def inOrder(node):
if node is None:
return []
return inOrder(node.left) + [node.key] + inOrder(node.right)
答案 1 :(得分:0)
解决方法是更新populate
方法:
class BST:
arr = []
def __init__(self):
self.height = 0
self.key = 0
self.left = None
self.right = None
def __str__(self):
return str(self.key)
def populate(self):
self.arr = []
temp = self
while temp.left != None or temp.right!=None:
self.arr.append(temp.key)
if temp.left!=None:
temp = temp.left
elif temp.right!=None:
temp = temp.right
if temp.left == None and temp.right==None:
self.arr.append(temp.key)
return self.arr
m1 = BST()
m1.key = 10
m2 = BST()
m2.key = 5
m1.left = m2
print(m1.left != None)
m3 = BST()
m3.key = 6
m2.left = m3
res = m1.populate()
print(res)
输出:
True
[10, 5, 6]