树:是一种抽象数据类型或者是实作这种类型的数据结构,用来模拟具有树状结构性质的数据集合
种类
二叉树存储
顺序存储:
遍历速度快,但操作复杂,占用空间大,不常用
链式存储:
应用场景
二叉树性质
二叉树的实现
采用链表存储,队列搜索插入点(广度优先遍历,完全二叉树)
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]#添加根节点到队列列表,self.root==None,也会使下面条件成立
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 breadth_travel(self)
"""广度遍历"""
if self.root is None#空树
return
queue =[self.root]
while queue:
cur_node=queue.pop(0)
print(cur_node.elem)
if cur_node.lchild is not None
queue.append(cur_node.lchild)
if cur_node.rchild is not None
queue.append(cur_node.rchild)
if __name__ == "__main__"
tree=Tree()
tree.add(9)
遍历
广度:层次遍历
深度:纵向遍历,先序(0-1-2),中序(1-0-2),后序(1-2-0)
def preorder(self,root):
"""递归先序遍历"""
if root == None:
return
print root.elem
self.preorder(root.lchild)
self.preorder(root.rchild)
def inorder(self,root)
"""递归中序遍历"""
if root == None:
return
self.inorder(root.lchild)
print root.elem
self.inorder(root.rchild)
def postorder(self,root)
"""递归后序遍历"""
if root == None:
return
self.postorder(root.lchild)
self.postorder(root.rchild)
print root.elem
由遍历顺序确定树
三种遍历顺序只要知道其中两个遍历结果便可确定一棵树