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;
}
相关推荐
2401_8898846615 分钟前
高性能计算通信库
开发语言·c++·算法
不想看见40436 分钟前
Hamming Distance位运算基础问题--力扣101算法题解笔记
算法
像污秽一样1 小时前
算法与设计与分析-习题4.1
算法·链表·排序算法
竹烟淮雨1 小时前
C语言指针概念详解:数组指针与二级指针的本质区别
c语言
lhc200906251 小时前
【作业】 贪心算法
算法·贪心算法
天若有情6731 小时前
循环条件隐藏陷阱:我发现了「同循环双条件竞态问题」
c++·学习·算法·编程范式·while循环··竞态
j_xxx404_1 小时前
C++算法:前缀和与哈希表实战
数据结构·算法·leetcode
We་ct2 小时前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
mit6.8242 小时前
tabbi风波|开源协议
算法
是梦终空1162 小时前
C++中的职责链模式变体
开发语言·c++·算法