【力扣100】226.翻转二叉树

添加链接描述

python 复制代码
# 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: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return root

        root.left,root.right=self.invertTree(root.right),self.invertTree(root.left)

        return root

思路:

  1. 对于这种左右对称或者一层一层的算法,首先想到递归
  2. 首先可以先写成这样,燃火再做剪枝:因为发现不管是否只有一个单独节点,都是可以被交换的
  3. 然后python3的独特简便交换机制:a , b = b , a


非递归做法

python 复制代码
# 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: Optional[TreeNode]) -> Optional[TreeNode]:
        q=collections.deque()
        q.append(root)

        while q:
            cur=q.popleft()
            if not cur:
                continue
            cur.left,cur.right=cur.right,cur.left
            q.append(cur.left)
            q.append(cur.right)

        return root

思路:

  1. 使用队列层序遍历二叉树
  2. continue的作用是跳出本次循环,直接进入下一次循环
相关推荐
2201_756989092 分钟前
C++中的事件驱动编程
开发语言·c++·算法
会飞的战斗鸡8 分钟前
JS中的链表(含leetcode例题)
javascript·leetcode·链表
多米Domi01113 分钟前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
2301_8223776514 分钟前
模板元编程调试方法
开发语言·c++·算法
故以往之不谏30 分钟前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°38 分钟前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困39 分钟前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 小时前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_811232981 小时前
低延迟系统C++优化
开发语言·c++·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode