二叉树创建
class TreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def create_binary_tree(input_list=[]):
'''
构建二叉树
:param input_list: 输入数列
:return: node
'''
if not isinstance(input_list,list):
return None
if input_list is None or len(input_list) == 0:
return None
data = input_list.pop(0)
if data is None:
return None
node = TreeNode(data)
node.left = create_binary_tree(input_list)
node.right = create_binary_tree(input_list)
return node
前序遍历
def pre_order_traversal(node):
'''
前序遍历
:param node: 二叉树结点
:return:
'''
if node is None:
return
print(node.data,end=',')
pre_order_traversal(node.left)
pre_order_traversal(node.right)
return node
中序遍历
def in_order_traversal(node):
'''
中序遍历
:param node: 二叉树结点
:return:
'''
if node is None:
return
in_order_traversal(node.left)
print(node.data,end=',')
in_order_traversal(node.right)
return node
后序遍历
def post_order_traversal(node):
'''
后序遍历
:param node: 二叉树结点
:return:
'''
if node is None:
return
post_order_traversal(node.left)
post_order_traversal(node.right)
print(node.data,end=',')
return node
广度优先遍历
def lev_order_traversal(node):
'''
广度优先遍历
:param node: 二叉树结点
:return:
'''
from queue import Queue
queue = Queue()
queue.put(node)
while not queue.empty():
node = queue.get()
print(node.data,end=',')
if node.left is not None:
queue.put(node.left)
if node.right is not None:
queue.put(node.right)
if __name__ == '__main__':
a = [3,2,9,1,0,10,5,7,8,6,4]
root = create_binary_tree(a)
create_binary_tree(root)
print('\n前序遍历')
pre_order_traversal(root)
print('\n中序遍历')
in_order_traversal(root)
print('\n后序遍历')
post_order_traversal(root)
print('\n广度优先遍历:')
lev_order_traversal(root)
参考:《漫画算法》