先序遍歷:節點 - 左孩子 - 右孩子
中序遍歷:左孩子 - 根結點 - 右孩子
後序遍歷:左孩子 - 右孩子 - 根結點
前序遍歷:- + a * b – c d / e f
中序遍歷:a + b * c – d – e / f
後序遍歷:a b c d – * + e f / -
class如果把print bin_tree.value放到前邊就是前序遍歷;放到中間就是中序遍歷;放到後邊就是後序遍歷。bintree():
def__init__(self, value, left=none, right=none):
self.value =value
self.left =left
self.right =right
definitial_tree():
a = bintree(1)
b = bintree(2)
c = bintree(7, a, b)
d = bintree(4)
e = bintree(3, c, d)
return
edef
pre_tr**ersal(bin_tree):
if bin_tree is
none:
return
bin_tree.value
if bin_tree.left is
notnone:
pre_tr**ersal(bin_tree.left)
#print bin_tree.value
if bin_tree.right is
notnone:
pre_tr**ersal(bin_tree.right)
#print bin_tree.value
test =initial_tree()
pre_tr**ersal(test)
前序遍歷實現:
def中序遍歷實現:pre_tr**ersal_no_cur(bin_tree):
if bin_tree is
none:
return
tree_stack =
while len(tree_stack) >0:
tmp =tree_stack.pop()
tmp.value
if tmp.right is
notnone:
if tmp.left is
notnone:
def後序遍歷非遞迴的實現的關鍵點,在於判斷出這個節點的右節點有沒有已經被遍歷過一遍了,所以實現1和實現2其實都是用來記住是否被遍歷過一遍了。mid_tr**ersal_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
notnone:
tmp =tmp.left
if len(tree_stack) >0:
tmp =tree_stack.pop()
tmp.value
tmp = tmp.right
實現2抓住的一點是,假設節點x,則x的右子節點遍歷輸出後,接著的一定是開始輸出x自己,所以可以用個q來儲存上個輸出的節點,然後用x.right判斷上個輸出的是不是右節點
後序遍歷實現1:
def後序遍歷實現2:after_tr**ersal_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
notnone:
tmp =tmp.left
if len(s1) >0:
tmp = s1[-1]
if s2[-1] == 1 or tmp.right is
none:
tmp =s1.pop()
s2.pop()
tmp.value
tmp =none
else
: s2[-1] = 1tmp = tmp.right
def這裡用到了deque模組,這裡其實可以相當於是棧和佇列,因為pop預設是pop出最後乙個,popleft則是pop出第乙個。after_tr**ersal_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
notnone:
tmp =tmp.left
while tmp.right is none or tmp.right ==q:
tmp.value
q =tmp
if len(s1) <=0:
return
tmp =s1.pop()
tmp = tmp.right
也可以直接像陣列那樣訪問,d[0]、d[-1]等
from collections importdeque
deflevel_tr**ersal(bin_tree):
if bin_tree is
none:
return
queue =deque()
while len(queue) >0:
tmp =queue.popleft()
tmp.value
if tmp.left is
notnone:
if tmp.right is
notnone:
delphi 遍歷檔案演算法 含遍歷目錄演算法
5 誰能幫我解釋一下這個遍歷檔案演算法.if searchrec.name and searchrec.name and searchrec.name img 這句是什麼意思?是大於還是小於.還是什麼意思.我是初學delphi的,對delphi的語法都不熟,想通過這個程式了解一下 謝謝哈 食用菌9級...
js陣列遍歷總結
1.原始方法 for var i 0 i 2.在es5中引入了foreach var arr 1,2,3,4 arr.foreach function value,index,arr 缺點 在foreach使用return會失效,break會報錯 都跳不出迴圈 3.for in 遍歷 只用於遍歷物件...
Map集合遍歷總結
建立物件,新增資料 mapscores new hashmap 泛型,其中string用於限定key的資料型別,integer用於顯示value的資料型別 scores.put tom 100 scores.put lucy 80 新增資料,map集合key不允許重複,否則以最後乙個為主 score...