当前位置:网站首页>【LeetCode】226.翻转二叉树
【LeetCode】226.翻转二叉树
2022-08-03 08:30:00 【酥酥~】
题目
给你一棵二叉树的根节点 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
题解
使用递归
从二叉树底部开始交换
/** * 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;
}
};
从上向下交换
/** * 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;
}
};
边栏推荐
- SQL每日一练(牛客新题库)——第5天:高级查询
- qt使用mysql数据库(自学笔记)
- sqlite 日期字段加一天
- HCIA实验(07)
- IDEA的database使用教程(使用mysql数据库)
- LeetCode 每日一题——622. 设计循环队列
- [Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
- swiper分类菜单双层效果demo(整理)
- netstat 及 ifconfig 是如何工作的。
- HCIP练习(OSPF)
猜你喜欢
随机推荐
DeFi明斯基时刻:压力测试与启示
Poke the myth of Web3?Poke the iron plate.
Unity编辑器扩展批量修改图片名称
redis stream 实现消息队列
36氪详情页AES
Redis分布式锁
MySQL or使索引失效
001-进程与线程
"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
ArcEngine(六)用tool工具实现拉框放大缩小和平移
SQL每日一练(牛客新题库)——第5天:高级查询
基于SSM开发的的小区物业管理系统小程序源码
IDEA2021.2安装与配置(持续更新)
mysql服务器上的mysql这个实例中表的介绍
长短期记忆网络 LSTM
数据监控平台
[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
【TPC-DS】DF的SQL(Data Maintenance部分)
ArcEngine(五)用ICommand接口实现放大缩小









