当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
随机推荐
【LeetCode】112.路径总和
What are pseudo-classes and pseudo-elements?The difference between pseudo-classes and pseudo-elements
牛客 - 最佳直播时间 (差分)
Qt 下拉复选框(MultiSelectComboBox)(一) 实现下拉框多选,搜索下拉框内容
【收获合辑】k-NN与检索任务的异同+jupyter转pdf
ArcEngine (4) Use of MapControl_OnMouseDown
NFT到底有哪些实际用途?
LeetCode 每日一题——622. 设计循环队列
HCIP练习03(重发布)
使用pipreqs导出项目所需的requirements.txt(而非整个环境)
greenplum role /user 管理
进程的创建
JMeter接口自动化发包与示例
English Grammar - Adverbial Clauses
英文语法-状语从句
QT中线程调用GUI主线程控件的问题
【无标题】
swiper分类菜单双层效果demo(整理)
MySQL数据库————数据库与vs的连接
Laya中关于摄像机跟随人物移动或者点击人物碰撞器触发事件的Demo