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;
}
相关推荐
旧梦吟9 分钟前
脚本网页 三人四字棋
前端·数据库·算法·css3·html5
凯_kyle12 分钟前
Python 算法竞赛 —— 基础篇(更新ing)
笔记·python·算法
lizz3120 分钟前
C++操作符重载深度解析
java·c++·算法
阿拉斯攀登25 分钟前
电子签名:笔迹特征比对核心算法详解
人工智能·算法·机器学习·电子签名·汉王
ytttr87328 分钟前
matlab进行利用遗传算法对天线阵列进行优化
开发语言·算法·matlab
一招定胜负29 分钟前
机器学习算法三:决策树
算法·决策树·机器学习
无限进步_30 分钟前
【C语言】队列(Queue)数据结构的实现与分析
c语言·开发语言·数据结构·c++·算法·链表·visual studio
李余博睿(新疆)40 分钟前
c++经典练习题-分支练习(2)
c++·算法
Dev7z42 分钟前
基于中心先验的全局对比度显著性检测算法
人工智能·算法·计算机视觉
重生之我是Java开发战士44 分钟前
【算法日记】排序算法:原理、实现、性能与应用
数据结构·算法·排序算法