二叉樹的前序、中序、後序非遞迴遍歷 python實現
阿新 • • 發佈:2019-01-31
前言
python中二叉樹的定義:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
前序
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
stack = [root]
while stack:
node = stack.pop()
if node:
ret.append(node.val)
stack.append(node.right)
stack.append(node.left)
return ret
通過使用棧先儲存要訪問的結點,這裡有一點需要注意的是,我們每次先將node的右結點加入到了stack中,然後再加入的是左結點,這樣我們就可以保證在每次stack彈棧的時候,左結點始終先彈出來了。
中序
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res, stack = [], []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return res
node = stack.pop()
res.append(node.val)
root = node.right
通過stack每次都儲存左子樹的所有結點,當左子樹已經全部加入了,這時候要訪問左子樹的葉子結點,然後需要轉向,加入當前結點的右結點,然後再繼續上述的過程。
後序
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
nodes = []
# to_visit是儲存結點的棧
to_visit = []
cur = root
last_node = None
# 如果當前結點或者要遍歷的結點不為空就持續遍歷
while cur or len(to_visit) != 0:
# 一直訪問左子樹,直至為空
if cur:
to_visit.append(cur)
cur = cur.left
else:
# 取到棧中最頂部的結點,然後判斷是否有右結點並且右結點是否已經訪問過
top_node = to_visit[-1]
if top_node.right and last_node != top_node.right:
cur = top_node.right
else:
# 訪問結點,並且將last_node記錄為當前訪問的結點
nodes.append(top_node.val)
last_node = top_node
to_visit.pop()
return nodes