手动创建一个二叉树
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2023/5/19 23:11
# @File : 二叉树的遍历.py
# @Software: PyCharm
"""
二叉树的遍历
二叉树的遍历方式:总共有四种:
"""
from collections import deque
#创建一个二叉树
class BiTreeNode:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
self.parent = None
def __repr__(self):
return self.data
a = BiTreeNode("A")
b = BiTreeNode("B")
c = BiTreeNode("C")
d = BiTreeNode("D")
e = BiTreeNode("E")
f = BiTreeNode("F")
g = BiTreeNode("G")
e.lchild = a
e.rchild = g
a.rchild = c
c.lchild = b
c.rchild = d
g.rchild = f
root = e
print("""""四种方法遍历树的结构""")
#前序遍历:
def pre_order(root):
if root:
print(root.data, end = ",")
pre_order(root.lchild)
pre_order(root.rchild)
#中序遍历:
def in_order(root):
if root:
in_order(root.lchild)
print(root.data,end=",")
in_order(root.rchild)
#后序遍历:
def post_order(root):
if root:
post_order(root.lchild)
post_order(root.rchild)
print(root.data,end=",")
#层次遍历:
def level(root):
queue = deque()#创建一个队列
queue.append(root) #将跟节点扔到队列里面去
while len(queue) > 0:#如果队列不为空
# 循环里面做的工作就是,队首出队,若存在给孩子结点,就会将孩子节点存放到队列里面,循环执行队首出队打印结点的信息和进队的操作
node = queue.popleft()#队首出队,第一个出的就是根节点
print(node.data,end=",")#打印节点的信息
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
print("前序遍历\n")
pre_order(root)
print("\n")
print("中序遍历\n")
in_order(root)
print("后序遍历\n")
post_order(root)
print("层次序遍历\n")
level(root)