前序遍历
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