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;
}
相关推荐
All for pursuit.1 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法1 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
圣保罗的大教堂1 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
剑指offer.2 小时前
嵌入式硬件-ARM芯片的启动
c语言·嵌入式硬件·嵌入式
hanlin032 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode
金士曼2 小时前
从规则到涌现:算法认知的三个层次
算法
AgentMaster3 小时前
数据资产化落地难题:5款数据中台系统架构对比与实施记录
大数据·人工智能·算法
Logic1013 小时前
C语言/数据结构动态规划题解:Kadane算法求最大子数组和——O(n)时间O(1)空间
c语言·数据结构·动态规划·贪心·时间复杂度·算法题·最大子数组和
鹿角片ljp3 小时前
从 Kimi Cyber Reasoning 学习网络安全推理数据集:从 Reasoning SFT 到安全 Agent 数据设计
数据结构·算法
圣保罗的大教堂4 小时前
leetcode 3629. 通过质数传送到达终点的最少跳跃次数 中等
leetcode