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;
}
相关推荐
ShallWeL1 小时前
【机器学习】(16)—— 数值数据
人工智能·python·算法·机器学习·数据分析
hongyucai1 小时前
详解rlinf强化学习四步曲
人工智能·python·算法·架构
变量未定义~1 小时前
ST表-龙骑士军团【算法赛】
数据结构·算法
小帽子_1232 小时前
储能 SOC/SOH 精准估算技术:储能工况下算法优化与误差修正方案
算法
hhlongg2 小时前
FFT分析
算法
水龙吟啸2 小时前
华为2026.6.17机考选择题+编程题【速刷敲黑板】
人工智能·深度学习·算法·华为
凌波粒2 小时前
LeetCode--53. 最大子序和(贪心算法)
算法·leetcode·贪心算法
Hesionberger2 小时前
快速求解完全平方数的最少数量
开发语言·数据结构·python·算法·leetcode·c#
c238562 小时前
《序列 DP:C++ 中的“最长”套路与编辑距离》
c++·算法·动态规划