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;
}
相关推荐
了一梨4 小时前
在Ubuntu中配置适配泰山派的交叉编译环境
linux·c语言·ubuntu
CQ_YM4 小时前
数据结构之单向链表
c语言·数据结构·链表
gihigo19984 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia5 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia5 小时前
go(基础08)——多态
算法·golang
leoufung5 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
亦是远方6 小时前
南京邮电大学使用计算机求解问题实验一(C语言简单编程练习)
c语言·开发语言·实验报告·南京邮电大学
im_AMBER6 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹6 小时前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD6 小时前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法