LeetCode C++ 226. Invert Binary Tree【Tree】简单
发布日期:2021-07-01 02:50:18
浏览次数:2
分类:技术文章
本文共 1886 字,大约阅读时间需要 6 分钟。
Invert a binary tree.
Example:
Input:4 / \ 2 7 / \ / \1 3 6 9
Output:
4 / \ 7 2 / \ / \9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
题意:翻转一棵二叉树。
思路1:先序遍历。代码如下:
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; swap(root->left, root->right); root->left = invertTree(root->left); root->right = invertTree(root->right); return root; }};
效率:
执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户内存消耗:9.3 MB, 在所有 C++ 提交中击败了52.45% 的用户
思路2:中序遍历。代码如下:
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; invertTree(root->left); //递归找到左结点 swap(root->left, root->right); invertTree(root->left); //此时左右结点已经交换 return root; }};
效率如下:
执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户内存消耗:9.2 MB, 在所有 C++ 提交中击败了61.82% 的用户
思路3:后序遍历。代码如下:
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; root->left = invertTree(root->left); root->right = invertTree(root->right); swap(root->left, root->right); return root; }};
效率:
执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户内存消耗:9.3 MB, 在所有 C++ 提交中击败了41.42% 的用户
思路4:层序遍历。代码如下:
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == nullptr) return root; queueq; q.push(root); while (!q.empty()) { TreeNode *t = q.front(); q.pop(); swap(t->left, t->right); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } return root; } };
效率:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:9.4 MB, 在所有 C++ 提交中击败了15.61% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108245798 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月14日 10时26分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
[7-03]反射小结
2019-05-04
[7-01]jvm
2019-05-04
[3-02]大型网站及其架构演进过程
2019-05-04
[7-01]jdbc
2019-05-04
[5-02]设计模式
2019-05-04
[5-03]事务和连接池
2019-05-04
[6-01]springioc
2019-05-04
[6-02]springaop
2019-05-04
[6-03]spring事务管理和框架整合
2019-05-04
[6-04]spring面试题
2019-05-04
[5-04]tomcat和servlet
2019-05-04
[11-01]mybatis
2019-05-04
[4-01]linux
2019-05-04
[9-01]git常见问题
2019-05-04
[13-1]类比路线
2019-05-04
[01-2]jkd动态代理和cglib代理的问题
2019-05-04
[02-01]如何学习新技术,比如java,学什么
2019-05-04
[02-02]工作任务非常多非常杂时如何处理
2019-05-04
[02-03]如何保证代码质量
2019-05-04
[16-1-01]大型网站架构演化
2019-05-04