二叉樹
簡介:
二叉樹是每個結點最多有兩個子樹的樹結構。通常子樹被稱作“左子樹”(left subtree)和“右子樹”(right subtree)。
二叉樹二叉樹的鏈式存儲:
將二叉樹的節點定義為一個對象,節點之間通過類似鏈表的鏈接方式來連接。
節點定義:
二叉樹的遍歷:
二叉樹的遍歷方式:
前序遍歷:EACBDGF
中序遍歷:ABCDEGF
后序遍歷:BDCAFGE
層次遍歷:EAGCFBD
代碼實現:
# _*_ coding=utf-8 _*_ """ 實現一個二叉樹結果,並進行遍歷 E / \ A G \ \ C F / \ B D """ from collections import deque class BinaryTree(object): def __init__(self, data): self.data = data self.child_l = None self.child_r = None # 創建 a = BinaryTree("A") b = BinaryTree("B") c = BinaryTree("C") d = BinaryTree("D") e = BinaryTree("E") f = BinaryTree("F") g = BinaryTree("G") # 構造節點關系 e.child_l = a e.child_r = g a.child_r = c c.child_l = b c.child_r = d g.child_r = f # 設置根 root = e def pre_order(tree): """ 前序遍歷:root -> child_l -> child_r :param tree: the root of tree :return: """ if tree: print(tree.data, end=',') # print("") pre_order(tree.child_l) pre_order(tree.child_r) def in_order(tree): """ 中序遍歷:child_l -> root -> child_r :param tree: :return: """ if tree: in_order(tree.child_l) print(tree.data, end=',') in_order(tree.child_r) def post_order(tree): """ 后序遍歷:child_l -> child_r -> root :param tree: :return: """ if tree: post_order(tree.child_l) post_order(tree.child_r) print(tree.data, end=',') def level_order(tree): """ 層次遍歷:E -> AG -> CF -> BD 使用隊列實現 :param tree: :return: """ queue = deque() queue.append(tree) # 先把根添加到隊列 while len(queue): # 隊列不為空 node = queue.popleft() print(node.data, end=',') if node.child_l: queue.append(node.child_l) if node.child_r: queue.append(node.child_r) pre_order(root) print('') in_order(root) print('') post_order(root) print('') level_order(root)