class Node:
"""
节点类
"""
def __init__(self, value=None, left=None, right=None):
self.val = value
self.left = left
self.right = right
class Tree:
"""
树类
"""
def __init__(self):
self.root = Node()
self.queue = []
def add(self, val):
"""
为树添加节点
"""
node = Node(value=val)
if self.root.val is None: # 如果树是空的,则当前节点为根节点
self.root = node
self.queue.append(self.root)
else:
treeNode = self.queue[0]
if treeNode.left is None:
treeNode.left = node
self.queue.append(treeNode.left)
else:
treeNode.right = node
self.queue.append(treeNode.right)
self.queue.pop(0) # 如果该节点存在左右子树,将此节点丢弃
def pre_order(self,node): # 先序遍历:根左右
print(node.val)
if node.left is not None:
self.pre_order(node.left)
if node.right is not None:
self.pre_order(node.right)
def center_order(self,node): # 中序遍历:左根右
if node.left is not None:
self.center_order(node.left)
print(node.val)
if node.right is not None:
self.center_order(node.right)
def post_order(self,node): # 后序遍历:左右根
if node.left is not None:
self.post_order(node.left)
if node.right is not None:
self.post_order(node.right)
print(node.val)
if __name__ == '__main__':
tree = Tree() # 新建一个树对象
for val in range(10):
tree.add(val)
tree.post_order(tree.root)