当前位置:网站首页>【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;
}
};
边栏推荐
- ArcEngine (1) Loading vector data
- Guava的Service
- 基于二次型性能指标的燃料电池过氧比RBF-PID控制
- Redis cluster concept and construction
- HCIP练习(OSPF)
- "Swordsman Offer" brush questions print from 1 to the largest n digits
- ArcEngine (5) use the ICommand interface to achieve zoom in and zoom out
- Redisson实现分布式锁
- 图解Kernel Device Tree(设备树)的使用
- Charles抓包工具学习记录
猜你喜欢
随机推荐
Evaluate:huggingface评价指标模块入门详细介绍
【微信小程序】底部有安全距离,适配iphone X等机型的解决方案
服务器资源监控工具-nmon、nmon_analyser
【论文笔记】基于动作空间划分的MAXQ自动分层方法
Docker starts mysql
dflow入门4——recurse&reuse&conditional
Laya中关于摄像机跟随人物移动或者点击人物碰撞器触发事件的Demo
qt使用mysql数据库(自学笔记)
HCIP实验(06)
The window of the chosen data flow
用diskpart的offline命令弹出顽固硬盘
Gauva的ListenableFuture
uni-app 顶部选项卡吸附效果 demo(整理)
并发之ReentrantLock
frp:开源内网穿透工具
《剑指Offer》刷题之打印从1到最大的n位数
PowerShell:执行 Install-Module 时,不能从 URI 下载
国内IT市场还有发展吗?有哪些创新好用的IT运维工具可以推荐?
"Swordsman Offer" brush questions print from 1 to the largest n digits
Logic Pro X自带音色库列表









