1. 二叉树
在计算机科学中,二叉树是每个节点最多有两个子树的树结构,通常子树被称为左子树和右子树。
2. 节点类
一个节点对象包含数据和指向两个子节点的引用,数据代表要存储的内容。
class Node(object):
"""节点"""
def __init__(self, val):
self.val = val
self.lchild = None
self.rchild = None
3. 二叉树添加节点
按层次添加,优先选择层次最小的,并且优先靠左添加节点。利用队列的先进先出可以实现添加节点。
class Tree(object):
"""二叉树"""
def __init__(self):
self.root = None
def add(self, item):
"""添加元素"""
queue = [self.root]
node = Node(item)
# 树为空
if self.root is None:
self.root = node
return
while queue:
cur = queue.pop(0)
if cur.lchild is not None:
queue.append(cur.lchild)
else:
cur.lchild = node
return
if cur.rchild is not None:
queue.append(cur.rchild)
else:
cur.rchild = node
return
4. 二叉树的层次遍历
- 根节点A入队
- 根节点A出队,访问A,将A的左右子树根节点B、C入队
- B出队,访问B,并将B的左右子树根节点入队
- 按照上述方法依次从队列出队并访问,直达队列为空
def breadth_travel(self):
"""层次遍历"""
if self.root is None:
return
queue = [self.root]
while queue:
cur = queue.pop(0)
print(cur.val, end=" ")
if cur.lchild is not None:
queue.append(cur.lchild)
if cur.rchild is not None:
queue.append(cur.rchild)
print("")
5. 先序遍历、中序遍历、后序遍历
- 先序遍历:根左右
- 中序遍历:左根右
- 后序遍历:左右根
def before_order(self, root):
"""先序遍历"""
if root == None:
return
print(root.val, end=" ")
self.before_order(root.lchild)
self.before_order(root.rchild)
def mid_order(self, root):
"""中序遍历"""
if root == None:
return
self.mid_order(root.lchild)
print(root.val, end=" ")
self.mid_order(root.rchild)
def after_order(self, root):
"""后序"""
if root == None:
return
self.after_order(root.lchild)
self.after_order(root.rchild)
print(root.val, end=" ")
6. 验证
if __name__ == '__main__':
tree = Tree()
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)
print("层次遍历:", end="")
tree.breadth_travel()
print("先序遍历:", end="")
tree.before_order(tree.root)
print("\n中序遍历:", end="")
tree.mid_order(tree.root)
print("\n后序遍历:", end="")
tree.after_order(tree.root)