python树的各种遍历
class Node(object):
def __init__(self, item):
self.item = item
self.left = None
self.right = None
class Tree(object):
def __init__(self):
self.root = None # 首先定义一个根节点
def add(self, item):
node = Node(item) # 将item其转化为Node型
queue = [self.root] # 用队列存储根节点
if self.root is None:
self.root = node # 如果根节点为空那么就将node赋值给根节点root
return
while queue: # 只要队列不为空就执行while语句里面的内容
cur_node = queue.pop(0) # cur_node用于存储队列弹出的元素
if cur_node.left is None:
cur_node.left = node # 判断左子树是否为空,为空则把node赋值给左子树
return
else:
queue.append(cur_node.left) # 如果不是空,则把cur_node.的左孩子放入队列当中
if cur_node.right is None: # 判断右子树是否为空,为空则把node赋值给右子树
cur_node.right = node
return
else:
queue.append(cur_node.right) # 如果不是空,则把cur_node.的右孩子放入队列当中
def breadth_travel(self):
"""层次遍历"""
if self.root is None:
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
print(cur_node.item, end=" ")
if cur_node.left is not None:
queue.append(cur_node.left)
if cur_node.right is not None:
queue.append(cur_node.right)
def preorder(self, root):
"""先序遍历"""
if root is None:
return
print(root.item, end=" ")
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
"""中序遍历"""
if root is None:
return
self.inorder(root.left)
print(root.item, end=" ")
self.inorder(root.right)
def afterorder(self, root):
"""后序遍历"""
if root is None:
return
self.afterorder(root.left)
self.afterorder(root.right)
print(root.item, end=" ")
def Excs(self):
exc = self.left
self.left = self.right
self.right = exc
def Exchange(self, root):
"""交换左右子树"""
queue = [self.root] # 用队列存储根节点
if root is None:
return
else:
while queue:
cur_node = queue.pop(0)
if cur_node.left or cur_node.right:
Tree.Excs(cur_node)
if cur_node.left:
queue.append(cur_node.left)
if cur_node.right:
queue.append(cur_node.right)
tree = Tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
tree.add(10)
tree.add(11)
tree.add(12)
tree.add(13)
tree.add(14)
tree.add(15)
# print("层次遍历结果:")
# tree.breadth_travel()
# print("\n")
# print("先序遍历结果:")
# tree.preorder(tree.root)
# print("\n")
# print("中序遍历结果:")
# tree.inorder(tree.root)
# print("\n")
# print("后序遍历结果:")
# tree.afterorder(tree.root)
# print("\n")
tree.Exchange(tree.root)
print("交换后层次遍历结果:")
tree.breadth_travel()