self.element = element
self.l_child = l_child
self.r_child = r_child
class Tree(object):
“”“树类”""
def init(self):
self.root = Node()
self.queue = []
def add_node(self, element):
“”“为树添加节点”""
node = Node(element)
如果树是空的,则对根节点赋值
if self.root.element == -1:
self.root = node
self.queue.append(self.root)
else:
tree_node = self.queue[0]
此结点没有左子树,则创建左子树节点
if tree_node.l_child is None:
tree_node.l_child = node
self.queue.append(tree_node.l_child)
else:
tree_node.r_child = node
self.queue.append(tree_node.r_child)
如果该结点存在右子树,将此节点丢弃
self.queue.pop(0)
def front_recursion(self, root):
“”“利用递归实现树的前序遍历”""
if root is