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;
}
相关推荐
Dfreedom.2 分钟前
【实战篇】分类任务全流程演示——决策树
人工智能·算法·决策树·机器学习·分类
阿梦Anmory3 分钟前
【RAG相关】深入理解混合检索:BM25关键词检索与RRF融合算法详解
算法
浅念-9 分钟前
LeetCode最短路必看:BFS算法原理+经典题解
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
aqiu11111110 分钟前
ACM校赛
算法
嵌入式小杰18 分钟前
一阶低通滤波入门教程:从原理到单片机 C 代码实现
c语言·开发语言·stm32·单片机·算法
kcuwu.23 分钟前
KNN算法技术博客
算法
叼烟扛炮27 分钟前
C++ 知识点02 输入输出
开发语言·c++·算法·输入输出
学会去珍惜37 分钟前
8天学会C语言编程第2天:变量、数据类型和输入/输出,3分钟上手
c语言·实战·变量·编程入门·输入输出
流年如夢40 分钟前
顺序表的应用 --> 简单通讯录的实现
c语言·数据结构
嵌入式小杰1 小时前
一阶卡尔曼滤波入门教程:从原理到单片机 C 代码实现
c语言·单片机