#定义树节点
class Node(object):
def __init__(self,data):
#data为树节点存储数据,left左子树,right右子树
self.elem = data
self.lchild = None
self.rchild = None
#创建二叉树
class BinTree(object):
def __init__(self):
self.root = None #初始化根节点为none
def add(self,data): #向树结构添加元素
node = Node(data)
# 如果树还是空树,则把该节点添加为根节点
if self.root is None:
self.root = node
else:
queue = [] # 模拟队列
queue.append(self.root) # 首先把根节点加入队列
# node = Node(data) #实例化根节点
# queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.lchild is None: #若根节点的左子树为None,添加左节点
cur_node.lchild = node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None: #若根节点的右子树为None,添加左节点
cur_node.rchild = node
return
else:
queue.append(cur_node.rchild)
def breadth_travel(self):
'''广度遍历'''
if self.root is None:
return
queue = [self.root]
last = self.root # 开始时,让 last 指向根节点
while queue:
cur_node = queue.pop(0)
print(cur_node.elem,end = " ")
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
nlast = cur_node.lchild # 加入左孩子时,让 nlast 指向左孩子
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
nlast = cur_node.rchild # 加入右孩子时,让 nlast 指向右孩子
if last == cur_node: # 如果 last 与当前弹出的节点相同时,说明该换行了
last = nlast
print('') # 打印换行
"""前序遍历:根>左>右"""
def preorder(self,node):
if node is None:
return
print(node.elem,end = " ")
self.preorder(node.lchild)
self.preorder(node.rchild)
"""中序遍历:左>根>右"""
def inorder(self,node):
if node is None:
return
self.inorder(node.lchild)
print(node.elem, end=" ")
self.inorder(node.rchild)
"""后序遍历:左>右>根"""
def posteorder(self,node):
if node is None:
return
self.postorder(node.lchild)
self.postorder(node.rchild)
print(node.elem, end=" ")
if __name__ == "__main__":
tree = BinTree()
tree.add(0)
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.breadth_travel()
tree.preorder(tree.root)
二叉树创建
最新推荐文章于 2024-04-12 19:34:23 发布