相关推荐
python coding with ChatGPT 打卡第12天| 二叉树:理论基础
python coding with ChatGPT 打卡第13天| 二叉树的深度优先遍历
python coding with ChatGPT 打卡第14天| 二叉树的广度优先遍历
文章目录
翻转二叉树
Key Points
- 只要把
每个节点的左右孩子翻转一下
,就可以达到整体翻转的效果 - 可选择深度优先遍历(递归遍历)或广度优先遍历(层序遍历)
相关题目
视频讲解
重点分析
递归遍历
前序:
def invertTreePreOrder(root):
if not root:
return None
root.left, root.right = root.right, root.left
invertTreePreOrder(root.left)
invertTreePreOrder(root.right)
return root
中序:
def invertTreeInOrder(root):
if not root:
return None
invertTreeInOrder(root.left)
root.left, root.right = root.right, root.left
invertTreeInOrder(root.left) # 注意:这里应该再次调用左子树
return root
在中序遍历中,我们先递归地处理左子树,然后交换当前节点的左右子节点,最后处理右子树。注意,由于我们在交换后再递归右子树,实际上我们需要两次递归左子树。
中序 法2:
def invertTree(root):
if not root:
return root
right = root.right # 先把右子树存起来
# 左
invertTree(root.left)
# 根
root.left, root.right = root.right, root.left
# 右
invertTree(right)
return root
后序:
def invertTreePostOrder(root):
if not root:
return No