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;
}
相关推荐
笨笨饿5 分钟前
#65_反激电源
stm32·单片机·嵌入式硬件·算法·硬件工程·个人开发
wengqidaifeng5 分钟前
数据结构:排序(下)---进阶排序算法详解
数据结构·算法·排序算法
MicroTech20256 分钟前
突破单机量子计算限制:MLGO微算法科技的新型分布式量子算法模拟平台实现高效验证
科技·算法·量子计算
没有天赋那就反复7 分钟前
C++里面引用参数和实参的区别
开发语言·c++·算法
wengqidaifeng11 分钟前
数据结构:排序(上)---基础排序算法详解
数据结构·算法·排序算法
Zlssszls17 分钟前
机器人马拉松的第二年,比的是其背后的隐形赛场:具身训练工具链
算法·机器人
shylyly_17 分钟前
sizeof 和 strlen的理解与区分
c语言·算法·strlen·sizeof
m0_7431064627 分钟前
【浙大&南洋理工最新综述】Feed-Forward 3D Scene Modeling(五)
人工智能·算法·计算机视觉·3d·几何学
Chockong1 小时前
11_vim自动插入文件头模板(.c/.cpp/.py/.txt)设置
c语言·vim
学会去珍惜9 小时前
是什么意思c语言
c语言·编程语言·底层开发·面向过程·系统软件