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;
}
相关推荐
头像很酷4 小时前
嵌入式虚拟化-xvisor-物理内存大管家
c语言·hypervisor·xvisor·嵌入式虚拟化
海绵宝宝转agent4 小时前
2026-10-16 4算法+1面经
算法
小poop4 小时前
基础排序算法详解——插入、选择与交换排序
算法·排序算法
青蓝智慧马老师4 小时前
想学数据分析但零基础,正确顺序不是先学 Python
大数据·人工智能·算法
嵌入式学习菌4 小时前
Modbus 透传和 Modbus 转发区别
c语言
jeo陽5 小时前
05-数组与冒泡排序:第一个数据结构与经典算法
c语言·数据结构·算法
水饺编程5 小时前
第2章:Linux 基础,mkdir 命令的简单入门
linux·c语言·汇编
鸽鸽程序猿5 小时前
【刷题册】hot21-25
算法
Keven_115 小时前
算法札记:记忆化搜索中面对多组数据的初始化
算法
happyprince5 小时前
02-具体观 · JevAny算法与实现剖析
人工智能·算法