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;
}
相关推荐
风筝在晴天搁浅26 分钟前
LeetCode CodeTop 82.删除排序链表中的重复元素Ⅱ
算法·leetcode·链表
1892280486129 分钟前
NV114固态MT29F16T08EWLEHD6-MES:E
人工智能·算法·缓存·性能优化
2601_9516457430 分钟前
C语言基础语法,分支语句
c语言·运算符·if语句·switch语句·分支语句
dtq042435 分钟前
C语言刷题函数1-判断素数(分支语句,函数两种方法)
c语言·开发语言·学习
Tairitsu_H38 分钟前
[LC优选算法#4] 滑动窗口 | 串联所有单词的⼦串 | 最⼩覆盖⼦串
c++·算法·滑动窗口
devilnumber40 分钟前
Java 二分查找(二分算法)详解 + 实战运用 + 核心坑点
java·开发语言·算法
洛水水42 分钟前
【力扣100题】84.字符串解码
算法·leetcode·职场和发展
AI科技星1 小时前
第四卷:橡皮泥江湖(拓扑学)
c语言·开发语言·网络·量子计算·agi·拓扑学
2601_951643881 小时前
关于C语言中getchar()的详细使用
c语言·输入输出·getchar()·eof·文件结束符
小七在进步1 小时前
数据结构:线性表之单链表
c语言·数据结构