当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢

【无标题】

110 MySQL interview questions and answers (continuous updates)

【论文笔记】基于动作空间划分的MAXQ自动分层方法

Redis分布式锁

Logic Pro X自带音色库列表

word之个人设置

审批流设计

《剑指Offer》刷题之打印从1到最大的n位数

Evaluate: A detailed introduction to the introduction of huggingface evaluation indicator module

The Transformer, BERT, GPT paper intensive reading notes
随机推荐
浅析什么是伪类和伪元素?伪类和伪元素的区别解析
关于Unity,Laya学习,第一步加载Unity加载场景
判断根节点是否等于子节点之和
LINGO 18.0软件安装包下载及安装教程
Docker启动mysql
【收获合辑】k-NN与检索任务的异同+jupyter转pdf
Redisson实现分布式锁
Gauva的ListenableFuture
Transformer、BERT、GPT 论文精读笔记
English Grammar - Adverbial Clauses
uni-app 顶部选项卡吸附效果 demo(整理)
安装mysql-workbench
【愚公系列】2022年07月 Go教学课程 026-结构体
The Transformer, BERT, GPT paper intensive reading notes
HCIP练习02(OSPF)
dflow入门5——Big step & Big parameter
【LeetCode】101.对称二叉树
积分商城系统设计
图解Kernel Device Tree(设备树)的使用
ArcEngine (4) Use of MapControl_OnMouseDown