当前位置:网站首页>【LeetCode】226. Flip the binary tree
【LeetCode】226. Flip the binary tree
2022-08-03 08:40:00 【Crispy~】
题目
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点.
示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:

输入:root = [2,1,3]
输出:[2,3,1]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目范围在 [0, 100] 内
-100 <= Node.val <= 100
题解
使用递归
Swap from the bottom of the binary tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr)
return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->right = left;
root->left = right;
return root;
}
};
Swap from top to bottom
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
void fun(TreeNode* root)
{
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
if(root->left)
fun(root->left);
if(root->right)
fun(root->right);
}
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr)
return nullptr;
fun(root);
return root;
}
};
边栏推荐
猜你喜欢

Using pipreqs export requirements needed for the project. TXT (rather than the whole environment)

内存模型之有序性

PowerShell:执行 Install-Module 时,不能从 URI 下载

36氪详情页AES

内存模型之可见性

服务器资源监控工具-nmon、nmon_analyser

Transformer、BERT、GPT 论文精读笔记

Exception: Dataset not found.解决办法

dflow部署简记

Machine learning (formula derivation and code implementation)--sklearn machine learning library
随机推荐
vim 折叠函数
Nacos使用实践
“==”和equals的区别
gpnmb+ gpnmb-AT2 cell空转映射 上皮细胞的空转映射
并发之多把锁和活跃性
Unity关于编辑器扩展自定义标签,方便扩展Inspector
Redis集群概念与搭建
图解Kernel Device Tree(设备树)的使用
【LeetCode】226.翻转二叉树
QImage的指针问题
AI mid-stage sequence labeling task: three data set construction process records
《剑指Offer》刷题之打印从1到最大的n位数
基于二次型性能指标的燃料电池过氧比RBF-PID控制
uni-app 顶部选项卡吸附效果 demo(整理)
ArcEngine (5) use the ICommand interface to achieve zoom in and zoom out
LeetCode 每日一题——622. 设计循环队列
MySQL2
关于Unity自定义Inspector面板的一些自定义编辑器扩展
行业洞察 | 如何更好的实现与虚拟人的互动体验?
合并两个有序链表