LeetCode //C - 226. Invert Binary Tree

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

Constraints:
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

From: LeetCode

Link: 226. Invert Binary Tree


Solution:

Ideas:

This function checks if the current node is NULL and, if not, it proceeds to swap the left and right child nodes. Then it recursively calls itself for the left and right children, which continues the process down the tree until all nodes have been visited and their children swapped.

Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct TreeNode* invertTree(struct TreeNode* root) {
    if (root == NULL) {
        return NULL;
    }
    
    // Swap the left and right children
    struct TreeNode* temp = root->left;
    root->left = root->right;
    root->right = temp;
    
    // Recursively invert the subtrees
    invertTree(root->left);
    invertTree(root->right);
    
    return root;
}
相关推荐
2501_941111247 分钟前
C++与自动驾驶系统
开发语言·c++·算法
2501_9411116920 分钟前
C++中的枚举类高级用法
开发语言·c++·算法
jz_ddk44 分钟前
[算法] 算法PK:LMS与RLS的对比研究
人工智能·神经网络·算法·信号处理·lms·rls·自适应滤波
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 106: 两个字符串的最小ASCII删除和
java·数据结构·算法·leetcode·深度优先
旭编1 小时前
小红的好矩形
c++·算法
小白程序员成长日记1 小时前
2025.11.12 力扣每日一题
算法·leetcode·职场和发展
Alex艾力的IT数字空间1 小时前
设计既保持高性能又兼顾可移植性的跨平台数据结构
数据结构·分布式·算法·微服务·中间件·架构·动态规划
leoufung1 小时前
贪心算法核心定理与应用——以 Gas Station 问题为例
算法·贪心算法
2501_941111461 小时前
C++与硬件交互编程
开发语言·c++·算法
未若君雅裁2 小时前
LeetCode 51 - N皇后问题 详解笔记
java·数据结构·笔记·算法·leetcode·剪枝