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;
}
相关推荐
热心网友俣先生2 小时前
2026年华数杯C 题 超详细解题思路
c语言·开发语言·人工智能
鹿角片ljp3 小时前
LeetCode 53. 最大子数组和
算法·leetcode·职场和发展
江屿风3 小时前
【科普】【差集&交集概念落地云相册】流食般投喂
开发语言·c++·笔记·算法·云相册
数模竞赛Paid answer3 小时前
2023年五一杯数学建模A题无人机定点投放问题求解全过程完整文档及程序
算法·数学建模·无人机·五一杯
科学实验家3 小时前
dp子序列问题,好难呀
算法
wabs66612 小时前
关于图论【卡码网117.软件构建的思考】
数据结构·算法·软件构建·图论·卡码网
mifengxing12 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
Tongzhi202613 小时前
从部署到运维:通芝科技无感考勤一体机的全流程效率解析
运维·数据结构·科技·算法·贪心算法
Wang's Blog13 小时前
AI Agent白手起家30: 动态示例选择器之根据长度选择 Few Shot 示例
算法
oyguyteggytrrwwwrt15 小时前
自制交叉线路识别算法
算法