翻转二叉树

时间复杂度是线性的,需要遍历每个节点。空间复杂度是线性的,最坏情况递归深度是线性的,即单链的情况。

  1. 本质是自底向上,递归到最底层,然后交换。
  2. 左子树更新为递归之后的右子树
  3. 右子树更新为递归之后的左子树
  4. 根始终保持不动
c 复制代码
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if ( root == nullptr ) return nullptr;
        TreeNode *left = invertTree( root->left );
        TreeNode *right = invertTree( root->right );
        root->left = right;
        root->right = left;
        return root;
    }
};
相关推荐
alphaTao2 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1233 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi3 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z18 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20819 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil20819 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil20820 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2081 天前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu1111111 天前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表