我想定義一個函數,它返回一個樹節點值的列表。該列表按照水平順序(從上到下,從左到右),如果缺少 孩子,則在其位置中插入「無」。從python二叉樹打印python列表
這是二叉樹執行
class BinaryTree:
def __init__(self, data, left = None, right = None):
self.left = left
self.right = right
def insert_left(self, data):
self.left = BinaryTree(data, left=self.left)
def insert_right(self, data):
self.right = BinaryTree(data, right=self.right)
def set_value(self, val):
self.key = val
def get_value(self):
return self.key
def create_string(self, indent):
string = str(self.key) + '---+'
if self.left:
string += '\n(l)' + indent + self.left.create_string(indent + ' ')
if self.right:
string += '\n(r)' + indent + self.right.create_string(indent + ' ')
return string
def __str__(self):
return self.create_string(' ')
def return_list(self, templist):
templist.append(self.key)
if self.left is None:
templist.append(None)
else:
self.left.return_list(templist)
if self.right is None:
templist.append(None)
else:
self.right.return_list(templist)
def main():
tree = BinaryTree(3)
tree.insert_left(29)
tree.insert_right(4)
right = tree.get_right_subtree()
left = tree.get_left_subtree()
left.insert_left(26)
right.insert_right(2)
right2 = right.get_right_subtree()
right2.insert_left(9)
templist = []
tree.return_list(templist)
main()
ahh我看到我做了什麼錯誤的謝謝! –