当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
随机推荐
关于Unity自定义Inspector面板的一些自定义编辑器扩展
《剑指Offer》刷题之打印从1到最大的n位数
JS函数获取本月的第一天和最后一天
36氪详情页AES
数据监控平台
【论文笔记】一种基于启发式奖赏函数的分层强化学习方法
关于Unity,Laya学习,第一步加载Unity加载场景
并发之固定运行和交替运行方案
服务器资源监控工具-nmon、nmon_analyser
Eject stubborn hard drives with diskpart's offline command
ArcEngine (six) use the tool tool to realize the zoom in, zoom out and translation of the pull box
DeFi明斯基时刻:压力测试与启示
Redis分布式锁
手把手教你如何自制目标检测框架(从理论到实现)
MySQL1
AcWing 3391. 今年的第几天?(简单题)
mysql5.7服务器The innodb_system data file 'ibdata1' must be writable导致无法启动服务器
【无标题】
Evaluate: A detailed introduction to the introduction of huggingface evaluation indicator module
牛客 - 鼠标的天选(字符串哈希)