writer:lIcht email:lIcht.gzl@gmail.com Date: 2019.9.15
树这种数据结构相比于一维的线性表来说提升了一个维度,属于二维的数据类型,在html、php等语言、文件管理、数据库管路以及AI学习领域等均用到了树的思想。其中二叉树是最基础的树的一种类型,在Python中同样以面向对象的思想实现树类的创建以及实现向树中添加节点,一种广度遍历以及三种深度遍历的方法的实现。其中三种深度遍历均用到了递归的思想是在树的比较重要的需要掌握的算法。
xxxxxxxxxx
# 完全二叉树的实现
# 重点在三种深度遍历
class Node(object):
"""树的节点"""
def __init__(self, item):
self.elem = item
self.lchild = None
self.rchild = None
class Tree(object):
"""二叉树"""
def __init__(self):
self.root = None
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.lchild is None:
cur_node.lchild = node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None:
cur_node.rchild = node
return
else:
queue.append(cur_node.rchild)
def breath_travel(self):
"""广度遍历(层次遍历)"""
if self.root is None:
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
print(cur_node.elem, end=" ")
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
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 postorder(self, node):
"""后序遍历,左子树-->右子树-->根节点"""
if node is None:
return
self.postorder(node.lchild)
self.postorder(node.rchild)
print(node.elem, end=" ")
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)
tree.breath_travel()
print("\n")
tree.preorder(tree.root)
print("\n")
tree.inorder(tree.root)
print("\n")
tree.postorder(tree.root)