当前位置:网站首页>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)
边栏推荐
- [high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (middle)
- urllib urllib2
- How to install MySQL 8.0 on rocky Linux and almalinux
- Source code migration from X86 platform to Kunpeng platform based on Kunpeng development kit [play with Huawei cloud]
- Seekg() [easy to understand]
- 灵感收集·创意写作软件评测:Flomo、Obsidian Memo、Napkin、FlowUs
- 灵感收集·创意写作软件评测:Flomo、Obsidian Memo、Napkin、FlowUs
- golang7_TCP编程
- June training (day 29) - divide and rule
- Don't build the wheel again. It is recommended to use Google guava open source tool class library. It is really powerful!
猜你喜欢

微信小程序:全新独家云开发微群人脉

微信小程序:全新獨家雲開發微群人脈

win10安装Monggodb的基本使用教程

vmware虚拟机的作用

Create an API rapid development platform, awesome!

Xiaobai learns MySQL - incremental statistical SQL requirements - windowing function scheme

sqlite3入门

Cloud native (31) | kubernetes chapter kubernetes platform basic pre installed resources

Thinkpad VMware 安装虚拟机出现此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态(问题解决方法)

灵感收集·创意写作软件评测:Flomo、Obsidian Memo、Napkin、FlowUs
随机推荐
[system design] proximity service
WinDbg debugging tool introduction
Openssl证书工具使用手册
systemd调试
Equivalence class partition method for test case design method
OpenSSL certificate tool user manual
Seekg() [easy to understand]
Notimplementederror: numpy() is only available when Eagle execution is enabled
Weserver publishing map service
【云驻共创】通过Rust语言计算加速技术突破图片识别性能瓶颈
【毕业季·进击的技术er】1076万毕业生,史上最难就业季?卷又卷不过,躺又躺不平,敢问路在何方?
投资人跌下神坛:半年0出手,转行送外卖
Leetcode question brushing: String 07 (repeated substring)
Want to make a wechat game for answering questions? Reading this article is enough
Why does ETL often become ELT or even let?
灵感收集·创意写作软件评测:Flomo、Obsidian Memo、Napkin、FlowUs
mysql多表查询
【黑马早报】中公教育市值蒸发逾2000亿;新东方直播粉丝破2000万;HM关闭中国首店;万科郁亮称房地产已触底;微信上线“大爆炸”功能...
GWD:基于高斯Wasserstein距离的旋转目标检测 | ICML 2021
Mondo rescue creates an image file (which is conducive to image damage recovery)