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;
}
相关推荐
人邮异步社区15 小时前
怎么把C语言学到精通?
c语言·开发语言
爱刷碗的苏泓舒15 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
烬羽18 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米18 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
星空露珠19 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
xiaobobo333020 小时前
C语言中宏定义宏名和宏值之间的关系
c语言·宏定义·语义型
QXWZ_IA21 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel21 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客21 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
风栖柳白杨21 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试