我想定义一个函数,该函数返回一棵树节点值的列表。这个列表是按照层次顺序排列的(从上到下,从左到右)。
例如,从上面展示的树中生成的列表将是:
这是二叉树实现。
例如,从上面展示的树中生成的列表将是:
[2, 29, 4, 26, None, None, 2, None, None, None, None, None, None, 9, None, end]
。这是二叉树实现。
class BinaryTree:
def __init__(self, data, left = None, right = None):
self.key = data
self.left = left
self.right = right
def insert(self, data):
node = self
while node is not None:
parent = node
if node.left is None:
parent.insert_left(data)
break
if node.right is None:
parent.insert_right(data)
break
node = node.left
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 get_left_subtree(self):
return self.left
def set_left(self, tree):
self.left = tree
def set_right(self, tree):
self.right = tree
def get_right_subtree(self):
return 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(' ')