1 概念
先序遍歷:節點 - 左孩子 - 右孩子
中序遍歷:左孩子 - 根結點 - 右孩子
后序遍歷:左孩子 - 右孩子 - 根結點
前序遍歷:- + a * b – c d / e f
中序遍歷:a + b * c – d – e / f
后序遍歷:a b c d – * + e f / -
2 python的前中后序遞歸算法實現
class BinTree(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def initial_tree(): a = BinTree(1) b = BinTree(2) c = BinTree(7, a, b) d = BinTree(4) e = BinTree(3, c, d) return e def pre_traversal(bin_tree): if bin_tree is None: return print bin_tree.value if bin_tree.left is not None: pre_traversal(bin_tree.left) #print bin_tree.value if bin_tree.right is not None: pre_traversal(bin_tree.right) #print bin_tree.value test = initial_tree() pre_traversal(test)
如果把print bin_tree.value放到前邊就是前序遍歷;放到中間就是中序遍歷;放到后邊就是后序遍歷。
3 python的前中后序非遞歸算法實現
前序遍歷實現:
def pre_traversal_no_cur(bin_tree): if bin_tree is None: return tree_stack = [] tree_stack.append(bin_tree) while len(tree_stack) > 0: tmp = tree_stack.pop() print tmp.value if tmp.right is not None: tree_stack.append(tmp.right) if tmp.left is not None: tree_stack.append(tmp.left)
中序遍歷實現:
def mid_traversal_no_cur(bin_tree): if bin_tree is None: return tree_stack = [] tmp = bin_tree while tmp is not None or len(tree_stack) > 0: while tmp is not None: tree_stack.append(tmp) tmp = tmp.left if len(tree_stack) > 0: tmp = tree_stack.pop() print tmp.value tmp = tmp.right
后序遍歷非遞歸的實現的關鍵點,在於判斷出這個節點的右節點有沒有已經被遍歷過一遍了,所以實現1和實現2其實都是用來記住是否被遍歷過一遍了。
實現2抓住的一點是,假設節點x,則x的右子節點遍歷輸出后,接着的一定是開始輸出x自己,所以可以用個q來保存上個輸出的節點,然后用x.right判斷上個輸出的是不是右節點
后序遍歷實現1:
def after_traversal_two_stack(bin_tree): if bin_tree is None: return s1 = [] s2 = [] tmp = bin_tree while tmp is not None or len(s1) > 0: while tmp is not None: s1.append(tmp) s2.append(0) tmp = tmp.left if len(s1) > 0: tmp = s1[-1] if s2[-1] == 1 or tmp.right is None: tmp = s1.pop() s2.pop() print tmp.value tmp = None else: s2[-1] = 1 tmp = tmp.right
后序遍歷實現2:
def after_traversal_single_stack(bin_tree): if bin_tree is None: return s1 = [] q = None tmp = bin_tree while tmp is not None or len(s1) > 0: while tmp.left is not None: s1.append(tmp) tmp = tmp.left while tmp.right is None or tmp.right == q: print tmp.value q = tmp if len(s1) <= 0: return tmp = s1.pop() s1.append(tmp) tmp = tmp.right
4 層次遍歷
這里用到了deque模塊,這里其實可以相當於是棧和隊列,因為pop默認是pop出最后一個,popleft則是pop出第一個。
也可以直接像數組那樣訪問,d[0]、d[-1]等
from collections import deque def level_traversal(bin_tree): if bin_tree is None: return queue = deque([]) queue.append(bin_tree) while len(queue) > 0: tmp = queue.popleft() print tmp.value if tmp.left is not None: queue.append(tmp.left) if tmp.right is not None: queue.append(tmp.right)