226. 翻转二叉树
原始题目链接:https://leetcode-cn.com/problems/invert-binary-tree/
解题思路:
实现方式有2种,一种是递归,一种是迭代。核心都是直接交换左右子树,只不过递归不需要用到额外的存储是深度优先遍历的方式,迭代需要用到队列来存储节点是广度优先遍历的方式。具体实现看代码及注释。
代码实现:
递归解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
# 递归结束条件:节点为空,返回null
if root is None:
return None
# 交换左右子树,并递归调用左子树、右子树
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
# 返回交换后的根节点
return root
迭代解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
# 存储层序遍历二叉树的节点队列
queue = [root]
while queue:
# 队列的元素出队
node = queue.pop(0)
# 交换当前遍历到的节点的左右子树
node.left, node.right = node.right, node.left
# 判断当前节点的左右子树是否存在,存在则入队继续循环交换下一层的左右子树
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
参考文献:
https://leetcode-cn.com/problems/invert-binary-tree/solution/dong-hua-yan-shi-liang-chong-shi-xian-226-fan-zhua/