前序遍歷
def pre_search(root: TreeNode):
res = []
if root is None:
return res
stack = [root] # 使用的是棧
while stack:
p = stack.pop()
res.append(p.val)
if p.right: # 先入右子樹
stack.append(p.right)
if p.left: # 後入左子樹
stack.append(p.left)
return res
後續遍歷
def post_search(root: TreeNode):
ans = []
if root is None:
return ans
stack = [root] # 使用的棧
while stack:
p = stack.pop()
ans.append(p.val)
if p.left: # 先入左子樹
stack.append(p.left)
if p.right: # 後入右子樹
stack.append(p.right)
return ans.reverse() # 最後翻轉
中序遍歷
def mid_sarch(root: TreeNode):
ans = []
if root is None:
return ans
stack = []
node = root
while stack or node: # 第一次通過node是否爲空判斷,後面都要通過stack判斷
# 先把左子樹都入到頭
while node:
stack.append(node)
node = node.left
# 此時 node 爲空
data = stack.pop()
ans.append(data.val)
node = data.right
return ans
層序遍歷
def level_search(root: TreeNode):
ans = []
if root is None:
return ans
queue = [root] # 層序遍歷使用的是隊列
while queue:
top = queue.pop(0)
ans.append(top.val)
if top.left: # 先進左子樹
queue.append(top.left)
if top.right: # 後進右子樹
queue.append(top.right)
return ans
一個方法包含所有遍歷方法的非遞歸遍歷
- 用樹的顏色標記節點狀態
- 白色代表未遍歷,黑色代表已經遍歷
- 因爲用的是棧,所以先入右子樹後入左子樹
class Solution:
def inorderTraversal(self, root: TreeNode):
if root is None:
return []
WHITE, BLACK = 0, 1
res = []
stack = [(WHITE, root)]
while stack:
color, node = stack.pop()
if color == WHITE: # 如果是白色的不遍歷,只遍歷黑色的
if node.right: # 先進右子樹
stack.append((WHITE, node.right))
stack.append((GRAY, node))
if node.left: # 後進左子樹
stack.append((WHITE, node.left))
else:
res.append(node.val)
return res
求樹深
def tree_max_hight(root: TreeNode):
if root is None:
return 0
queue = [(1, root)]
max_hight = 0
while queue:
hight, node = queue.pop(0)
max_hight = max(max_hight, hight)
if node.left:
queue.append((hight + 1, node.left))
if node.right:
queue.append((hight + 1, node.right))
return max_hight
最近公共祖先
def node_father(root, q, p): # 最近公共祖先
if root is None:
return None
if root == q or root == p:
return root
left = node_father(root.left, q, p)
right = node_father(root.right, q, p)
if left and right:
return root
if left:
return left
if right:
return right
二叉樹翻轉
先翻轉左子樹,再翻轉右子樹
最後把兩棵樹翻轉
def invertTree(root: TreeNode):
if root is None:
return root
root.left = invertTree(root.left)
root.right = invertTree(root.right)
root.left, root.right = root.right, root.left
return root