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;
}
相关推荐
m0_62949473几秒前
LeetCode 热题 100-----13.最大子数组和
数据结构·算法·leetcode
0xR3lativ1ty7 分钟前
大模型算法原理高频题解析
算法
故事还在继续吗9 分钟前
STL 容器算法手册
开发语言·c++·算法
田梓燊9 分钟前
力扣:94.二叉树的中序遍历
数据结构·算法·leetcode
啊我不会诶9 分钟前
2023西安邀请赛vp补题
c++·算法
khalil102010 分钟前
代码随想录算法训练营Day-38动态规划06 | 322. 零钱兑换、279.完全平方数、139.单词拆分、多重背包、总结
数据结构·c++·算法·leetcode·动态规划
jimy114 分钟前
C语言历史版本和gnu扩展版本
c语言·算法·gnu
shehuiyuelaiyuehao15 分钟前
关于算法14,15解决一些问题
算法
探序基因15 分钟前
单细胞转录组Seurat去批次-FastMNN算法及大细胞量评测
linux·算法
阿Y加油吧16 分钟前
二刷 LeetCode:300. 最长递增子序列 & 152. 乘积最大子数组 复盘笔记
笔记·算法·leetcode