当前位置:网站首页>leetcode:226. Flip binary tree
leetcode:226. Flip binary tree
2022-06-29 14:03:00 【uncle_ ll】
226. Flip binary tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/invert-binary-tree/
Give you the root node of a binary tree root , Flip this binary tree , And return its root node .
Example 1:
Input :root = [4,2,7,1,3,6,9]
Output :[4,7,2,9,6,3,1]
Example 2:

Input :root = [2,1,3]
Output :[2,3,1]
Example 3:
Input :root = []
Output :[]
Tips :
- The number of nodes in the tree ranges from [0, 100] Inside
- -100 <= Node.val <= 100
solution
- recursive : Start at the root node , Swap two child nodes , Then recursively process the two child nodes
- bfs loop : Use a queue to store the nodes of each tier , Then each time from the queue header pop Let's get a node , Swap the child nodes of this node , If the child node is not empty , Add child nodes to the queue ;
Code implementation
recursive
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
# Recursion end condition
if not root or (not root.left and not root.right):
return root
# Process this node
root.left, root.right = root.right, root.left
# Recursive next node
self.invertTree(root.left)
self.invertTree(root.right)
return root
c++ Realization
/** * 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 || (root->left == nullptr && root->right == nullptr))
return root;
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
if (root->left != nullptr)
invertTree(root->left);
if (root->right != nullptr)
invertTree(root->right);
return root;
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N) The space used is determined by the depth of the recursive stack , It is equal to the height of the current node in the binary tree . On average , The height of a binary tree has a logarithmic relationship with the number of nodes , namely O ( l o g N ) O(log N) O(logN) . And in the worst case , Trees form chains , The space complexity is O ( N ) O(N) O(N).
BFS loop
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root or (not root.left and not root.right):
return root
stack = [root]
while stack:
node = stack.pop(0)
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
c++ Realization
/** * 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 || (root->left == nullptr && root->right == nullptr))
return root;
queue<TreeNode*> qs;
qs.push(root);
TreeNode *tmp;
while(qs.size() > 0) {
tmp = qs.front();
qs.pop();
TreeNode * tmp2 = tmp->left;
tmp->left = tmp->right;
tmp->right = tmp2;
if (tmp->left != nullptr)
invertTree(tmp->left);
if (tmp->right != nullptr)
invertTree(tmp->right);
}
return root;
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
边栏推荐
- [graduation season · advanced technology Er] 10.76 million graduates, the most difficult employment season in history? I can't roll it up again. I lie down again and again. Where is the road?
- How to install MySQL 8.0 on rocky Linux and almalinux
- STM32 watchdog study
- WinDbg common commands
- Stable currency risk profile: are usdt and usdc safe?
- Cicd introduction [easy to understand]
- 微信小程序:云开发表白墙微信小程序源码下载免服务器和域名支持流量主收益
- Return value‘s Lifetime
- Hash hash game system development explanation technology -- hash game system development solution analysis
- ##Mondo Rescue制作镜像文件(有利于镜像损坏恢复)
猜你喜欢

leetcode:226. 翻转二叉树

手把手教你在windows上安装mysql8.0最新版本数据库,保姆级教学

Hundreds of CVPR people were recruited as new champions. Emoji became a "court witness". M2 MBP was exposed that the hard disk speed was reduced. Today, more big news is here

Teach you how to install the latest version of mysql8.0 database on windows, nanny level teaching

goby如何导出扫描结果

Detailed explanation of PDB symbol library files

WinDbg debugging tool introduction

Problems in replacing RESNET convolution of mmdet with ghost convolution group

Create an API rapid development platform, awesome!
![[graduation season] it's worth it all the way over the past four years -- advice from the senior students](/img/26/d6363603ff57730970497789a05265.png)
[graduation season] it's worth it all the way over the past four years -- advice from the senior students
随机推荐
手把手教你在windows上安装mysql8.0最新版本数据库,保姆级教学
Mondo rescue creates an image file (which is conducive to image damage recovery)
Create an API rapid development platform, awesome!
How goby exports scan results
Notimplementederror: numpy() is only available when Eagle execution is enabled
go-zero微服务实战系列(七、请求量这么高该如何优化)
Cloud native (31) | kubernetes chapter kubernetes platform basic pre installed resources
Dynamic feedback load balancing strategy based on Cluster
Hundreds of CVPR people were recruited as new champions. Emoji became a "court witness". M2 MBP was exposed that the hard disk speed was reduced. Today, more big news is here
揭秘百度智能测试在测试自动执行领域实践
Introduction to esp8266: three programming methods "suggestions collection"
人不成熟的特征
【云驻共创】通过Rust语言计算加速技术突破图片识别性能瓶颈
golang代码规范整理
Application of ansvc reactive power compensation device in a shopping mall in Hebei
Wechat applet: repair collection interface version cloud development expression package
System. Currenttimemillis() and system Nanotime() which is faster? Most people get the wrong answer!
Equivalence class partition method for test case design method
深度学习的坎坷六十年
微信小程序:云开发表白墙微信小程序源码下载免服务器和域名支持流量主收益