樹的三種遍歷 遞迴和非遞迴形式的python實現

2021-09-27 01:14:36 字數 2400 閱讀 9710

class

treenode

(object):

#建立樹的結構

def__init__

(self,x)

: self.val=x

self.left=

none

self.right=

none

#遞迴形式

#前序遍歷

defpreorderrecusive

(root)

:if root==

none

:return

none

print

(root.val)

preorderrecusive(root.left)

preorderrecusive(root.right)

#中序遍歷

defmidorderrecusive

(root)

:if root==

none

:return

none

midorderrecusive(root.left)

print

(root.val)

midorderrecusive(root.right)

#後序遍歷

deflateorderrecusive

(root)

:if root==

none

:return

none

lateorderrecusive(root.left)

lateorderrecusive(root.right)

print

(root.val)

#非遞迴形式

#前序遍歷

defpreorder

(root)

:if root==

none

:return

none

tmp=root

stack=

while tmp or stack:

#當tmp非空或者stack非空

while tmp:

print

(tmp.val)

tmp=tmp.left

node=stack.pop(

) tmp=node.right#要去迴圈的下乙個頭

#中序遍歷

defmidorder

(root)

:if root==

none

:return

none

tmp=root

stack=

while tmp or stack:

#當tmp非空或者stack非空

while tmp:

#print(tmp.val)

tmp=tmp.left

node=stack.pop(

)print

(node.val)

tmp=node.right#要去迴圈的下乙個頭

#後序遍歷

deflateorder

(root)

:if root==

none

:return

none

tmp=root

stack=

while tmp or stack:

#當tmp非空或者stack非空

while tmp:

#print(tmp.val)

tmp=tmp.left

node=stack[-1

] tmp=node.right#要去迴圈的下乙個頭

if node.right==

none

: node=stack.pop(

)print

(node.val)

while stack and node==stack[-1

].right:

node=stack.pop(

)print

(node.val)

#建立一棵樹

if __name__==

'__main__'

: t1=treenode(1)

t2 = treenode(2)

t3 = treenode(3)

t4 = treenode(4)

t5 = treenode(5)

t6 = treenode(6)

t7 = treenode(7)

t1.left=t2

t1.right=t3

t2.left=t4

t2.right=t5

t3.left=t6

t3.right=t7

lateorder(t1)

樹的三種遍歷(遞迴和非遞迴)

typedef struct bitnode bitnode,bitree 先序遍歷 根左右 遞迴 void lastorder bitnode root void preorder bitnode root 中序遍歷 左根右 遞迴 void midorder bitnode root 後續遍歷 左...

樹的遞迴和非遞迴遍歷

利用迴圈和棧實現前序 中序和後序遍歷 利用佇列實現層次遍歷 typedef struct node bitree stacks 前序遍歷 針對乙個根結點,先輸出其根結點值,再push其所有左結點,然後再彈出乙個結點取其右結點作為新的根結點。void preorder bitree t 前序遍歷的非遞...

二叉樹的七種遍歷 三種遞迴,三種非遞迴

二叉樹的標頭檔案 不包含裡面所用的棧和佇列的標頭檔案 在非遞迴裡面會用到,非遞迴只闡述思想,不寫 遞迴 如下 ifndef btree h define btree h typedef char btdatatype typedef struct binarytreenode btnode 通過前序...