[LeetCode] Invert Binary Tree
After reading the quote below the problem, you will be motivated to solve it immediately :-) Well, indeed it is also relative easy. The process of inverting a binary tree is simply 3 steps:
- Swap the
left
subtree and theright
subtree; - Invert the
left
subtree; - Invert the
right
subtree.
So we immediately have the following simple recursive solution.
1 class Solution { 2 public: 3 TreeNode* invertTree(TreeNode* root) { 4 if (!root) return NULL; 5 swap(root -> left, root -> right); 6 root -> left = invertTree(root -> left); 7 root -> right = invertTree(root -> right); 8 return root; 9 } 10 };
Well, you may also want to challenge yourself to solve it iteratively. The iterative solution is basically a level-order traversal. Push all the nodes of the same level to a queue and then swap their left
subtree and right
subtree and iterate over their subtrees.
The code is as follows.
1 class Solution { 2 public: 3 TreeNode* invertTree(TreeNode* root) { 4 if (!root) return NULL; 5 queue<TreeNode*> level; 6 level.push(root); 7 while (!level.empty()) { 8 TreeNode* node = level.front(); 9 level.pop(); 10 swap(node -> left, node -> right); 11 if (node -> left) level.push(node -> left); 12 if (node -> right) level.push(node -> right); 13 } 14 return root; 15 } 16 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档