复习 深度遍历(先序中序后序)

 1 class Node(object):
 2     '''定义一个结点,有左孩子和右孩子'''
 3     def __init__(self,data):
 4         # 结点数据
 5         self.data = data
 6         # 左、右 孩子指向为空
 7         self.lchild = None
 8         self.rchild = None
 9 
10 class BinaryTree(object):
11     '''二叉树'''
12     def __init__(self):
13         # 根结点默认为空
14         self.root = None
15 
16     def add(self,data):
17         # 添加数据到二叉树中 向最后进行添加数据
18         # 处理顺序:父结点 左孩子 右孩子
19         node = Node(data)
20         # 如果为空树
21         if self.root is None:
22             self.root = node
23             # 空树,加入数据则放在根节点处
24             return
25         queue = [self.root]
26         # 添加根节点,作为存在该结点的标志
27         while queue:
28             # 如果 queue 不为空
29             cur_node = queue.pop(0)
30             # 当前结点指向根节点,取第一个元素
31             if cur_node.lchild is None :
32                 # 如果左结点为空
33                 cur_node.lchild = node
34                 return
35             else:
36                 # 添加到指针内,证明存在左结点
37                 queue.append(cur_node.lchild)
38             if cur_node.rchild is None:
39                 # 如果右结点为空
40                 cur_node.rchild = node
41                 return
42             else:
43                 # 添加到指针内,证明存在右结点
44                 queue.append(cur_node.rchild)
45 
46     def pre_order(self,node):
47         '''先序遍历 -> 根左右'''
48         if node is None:
49             return
50         print(node.data,end = " ")
51         self.pre_order(node,lchild)
52         # 一直递归左面结点,返回后遍历右面
53         self.pre_order(node,rchild)
54         # 开始遍历右侧,直到为空
55 
56     def in_order(self,node):
57         '''中序遍历 -> 左根右'''
58         if node is None:
59             return
60         self.in_order(node,lchild)
61         # 一直递归左面结点
62         print(node.data,end = " ")
63         # 打印输出数据
64         self.in_order(node,rchild)
65         # 遍历右侧数据
66 
67 
68     def post_order(self,node):
69         '''后序遍历 -> 左右根'''
70         if node is None:
71             return
72         self.post_order(node,lchild)
73         # 一直递归左面结点
74         self.post_order(node,rchild)
75         # 一直递归右面结点
76         print(node.data,end = " ")

2020-04-18

猜你喜欢

转载自www.cnblogs.com/hany-postq473111315/p/12725386.html