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;
}
相关推荐
Yue丶越1 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
小白程序员成长日记1 小时前
2025.11.24 力扣每日一题
算法·leetcode·职场和发展
有一个好名字1 小时前
LeetCode跳跃游戏:思路与题解全解析
算法·leetcode·游戏
AndrewHZ2 小时前
【图像处理基石】如何在图像中提取出基本形状,比如圆形,椭圆,方形等等?
图像处理·python·算法·计算机视觉·cv·形状提取
蓝牙先生2 小时前
简易TCP C/S通信
c语言·tcp/ip·算法
2501_941870563 小时前
Python在高并发微服务数据同步与分布式事务处理中的实践与优化
leetcode
Old_Driver_Lee3 小时前
C语言常用语句
c语言·开发语言
松涛和鸣4 小时前
从零开始理解 C 语言函数指针与回调机制
linux·c语言·开发语言·嵌入式硬件·排序算法
2501_941147715 小时前
高并发微服务架构Spring Cloud与Dubbo在互联网优化实践经验分享
leetcode
稚辉君.MCA_P8_Java6 小时前
Gemini永久会员 Java中的四边形不等式优化
java·后端·算法