# #-*- coding:utf-8 -*-
# # @Author:zhangy
# # @Time:2019-09-27 11:25
# # reference:https://github.com/EchoLLLiu/DataStructure/tree/master/ch04tree
#
class TreeNode:
'''二叉搜索树节点的定义'''
def __init__(self,val,left=None,right=None):
self.val = val
self.left = left
self.right = right
class OperationTree:
def create(self,List):
'''二叉搜索树插入操作'''
root = TreeNode(List[0])
lens = len(List)
if lens >= 2:
root.left = self.create(List[1])
if lens >= 3:
root.right = self.create(List[2])
return root
def query(self,root,data):
'''二叉树查找操作'''
if root == None:
return False
if root.val == data:
return True
elif root.left:
return self.query(root.left,data)
elif root.right:
return self.query(root.right,data)
def pre_order(self,root):
'''先序输出二叉树'''
if root == None:
return
print root.val
self.pre_order(root.left)
self.pre_order(root.right)
def in_order(self,root):
'''中序输出二叉树'''
if root == None:
return
self.in_order(root.left)
print root.val
self.in_order(root.right)
def bac_order(self,root):
'''后续输出二叉树'''
if root == None:
return
self.bac_order(root.left)
self.bac_order(root.right)
print root.val
def BFS(self,root):
if root == None:
return
queue = []#保存节点
queue.append(root)
while queue:
#拿出队首节点
currentNode = queue.pop(0)
print currentNode.val
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
def DFS(self,root):
'''深度优先'''
if root == None:
return
stack = [] #用栈来保存访问节点
stack.append(root)
while stack:
currentNode = stack.pop()#取后加入的
print currentNode.val
if currentNode.right:
stack.append(currentNode.right)
if currentNode.left:
stack.append(currentNode.left)
if __name__ == '__main__':
List1 = [1, [2, [4, [8], [9]], [5]], [3, [6], [7]]]
op = OperationTree()
tree1 = op.create(List1)
print('先序打印:')
op.pre_order(tree1)
print('中序打印:')
op.in_order(tree1)
print('后序打印:')
op.bac_order(tree1)
print('广度优先:')
op.BFS(tree1)
print('深度优先:')
op.DFS(tree1)
输出结果:
C:\Users\Administrator\Anaconda3\envs\py2\python.exe "F:/ML2/算法导论/practice/12.2 二叉树.py"
先序打印:
1
2
4
8
9
5
3
6
7
中序打印:
8
4
9
2
5
1
6
3
7
后序打印:
8
9
4
5
2
6
7
3
1
广度优先:
1
2
3
4
5
6
7
8
9
深度优先:
1
2
4
8
9
5
3
6
7
Process finished with exit code 0