Python 二叉樹的非遞迴遍歷

2021-09-22 20:12:49 字數 2003 閱讀 9850

二叉樹類實現

class bintnode:

def __init__(self, dat, left = none, right = none):

self.data = data

self.left = left

self.right = right

統計樹中節點個數

def count_bintnodes(t):

if t is none:

return 0

else:

return 1 + count_bintnode(t.left) \

+ count_bintnode(t.right)

求二叉樹所有數值和

def sum_bintnodes(t):

if t is none:

return 0

else:

return t.dat + sum_bintnodes(t.left) \

+ sum_bintnodes(t.right)

非遞迴的先根序遍歷函式

def preorder_nonrec(t, proc):

s = sstack()

while t is not none or s.is_empty():

while t is not none: # 沿左分支下行

proc(t.data) # 先根序先處理根資料

s.push(t.right) # 右分支入棧

t = t.left

t = s.pop()

preorder_nonrec(tree, lambda x:print(x, end=" "))

通過生成器函式遍歷

def preorder_elements(t):

s = sstack()

while i is not none or not s.is_empty():

while t is not none:

s.push(t.right)

yield t.data

t = t.left

t = s.pop()

中序非遞迴遍歷

def inorder_nonrec(t, proc):

s = sstack()

while t is not none or s.is_empty():

while t is not none:

s.push(t)

t = t.left

t = s.pop()

proc(t.data)

t = t.right

非遞迴的後根序遍歷

def postorder_nonrec(t, proc):

s = sstack()

while t is not none or not s.is_empty():

while t is not none: # 下行迴圈, 直到棧頂的兩子樹空

s.push(t)

t = t.left if t.left is not none else t.right

t = s.pop() # 棧頂是應訪問節點

proc(t.data)

if not s.is_empty() and s.top().left == t:

t = s.top().right # 棧不為空且當前節點是棧頂的左子節點

else:

t = none # 沒有右子樹或右子樹遍歷完畢, 強迫退棧

二叉樹的非遞迴遍歷(python

class treenode def init self,x self.val x self.left none self.right none class solution object 二叉樹非遞迴前序序遍歷 def pre order self,root if not root return ...

二叉樹遍歷(遞迴 非遞迴)

二叉樹以及對二叉樹的三種遍歷 先根,中根,後根 的遞迴遍歷演算法實現,以及先根遍歷的非遞迴實現。node public class node public node left public node right public object value 遍歷訪問操作介面 public inte ce ...

二叉樹非遞迴遍歷

二叉樹非遞迴遍歷的幾個要點 1 不管前序 中序還是後序,它們的遍歷路線 或者說是回溯路線,先沿左邊一直走到盡頭,然後回溯到某節點,並跳轉到該節點的右孩子 如果有的話 然後又沿著這個有孩子的左邊一直走到盡頭 都是一樣的。2 明確每次回溯的目的。比如,前序回溯的目的是為了訪問右子樹 中序回溯的目的是為了...