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;
}
相关推荐
2401_838472514 分钟前
C++图形编程(OpenGL)
开发语言·c++·算法
-dzk-8 分钟前
【代码随想录】LC 203.移除链表元素
c语言·数据结构·c++·算法·链表
进击的小头31 分钟前
陷波器实现(针对性滤除特定频率噪声)
c语言·python·算法
知无不研34 分钟前
冒泡排序算法
算法·冒泡排序·排序
毅炼36 分钟前
hot100打卡——day17
java·数据结构·算法·leetcode·深度优先
Tisfy39 分钟前
LeetCode 3010.将数组分成最小总代价的子数组 I:排序 OR 维护最小次小
算法·leetcode·题解·排序·最小次小值
Learn Beyond Limits44 分钟前
文献阅读:A Probabilistic U-Net for Segmentation of Ambiguous Images
论文阅读·人工智能·深度学习·算法·机器学习·计算机视觉·ai
m0_736919101 小时前
编译器命令选项优化
开发语言·c++·算法
naruto_lnq1 小时前
C++中的工厂方法模式
开发语言·c++·算法
千逐-沐风1 小时前
SMU-ACM2026冬训周报2nd
算法