# #-*- 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