LeetCode #226 - Invert Binary Tree - Easy
来源:互联网 发布:网络金融的发展趋势 编辑:程序博客网 时间:2024/04/26 13:45
Problem
Invert a binary tree.
Example
4 / \ 2 7 / \ / \1 3 6 9-> 4 / \ 7 2 / \ / \9 6 3 1
Algorithm
整理一下题意:翻转一棵二叉树。
首先想到的当然是递归解法。对每个节点,都翻转左右子树。
代码如下。
//递归版本,用时0msclass Solution {public: TreeNode* invertTree(TreeNode* root) { if(root==NULL) return NULL; TreeNode* temp=root->left; root->left=invertTree(root->right); root->right=invertTree(temp); return root; }};
然而,
题目中写了这么一句
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 fuck off.
那么这题真有这么简单?刚刚的递归解法AC了,那么尝试一下非递归解法吧。
要翻转整棵树,那么对每个左子和右子都要翻转。由于左子和右子交换时,左子和右子的子树也随之交换,所以只要对左子右子做处理即可。交换的左子和右子必然是在同一层的,那么可以考虑通过层次遍历来实现。
在层次遍历的过程中,对每个左子和右子都进行交换。对子树为NULL的情况稍作处理即可。
代码如下。
//非递归版本,用时3msclass Solution {public: TreeNode* invertTree(TreeNode* root) { if(root==NULL) return NULL; queue<TreeNode*> q; TreeNode* p; TreeNode* temp; q.push(root); while(!q.empty()){ p=q.front(); q.pop(); temp=p->left; p->left=p->right; p->right=temp; if(p->left!=NULL) q.push(p->left); if(p->right!=NULL) q.push(p->right); } return root; }};
提交代码,AC。没想到用时反而比递归版本还长。所以Max Howell那句话真是在开玩笑嘛…
0 0
- [Leetcode 226, Easy] Invert Binary Tree
- <LeetCode><Easy>226Invert a binary tree
- LeetCode #226 - Invert Binary Tree - Easy
- 【Leetcode-easy-226】Invert Binary Tree
- 【leetcode】【Easy】【226. Invert Binary Tree】【tree】
- leetcode 226 Invert Binary Tree(难易度:Easy)
- Leetcode 226. Invert Binary Tree (Easy) (cpp)
- LeetCode 226. Invert Binary Tree (Easy)
- Invert Binary Tree(easy)
- Easy 226题 Invert Binary Tree
- Leetcode[226]-Invert Binary Tree
- LeetCode 226 Invert Binary Tree
- Invert Binary Tree - LeetCode 226
- leetcode[226]:Invert Binary Tree
- leetcode 226: Invert Binary Tree
- Leetcode 226 Invert Binary Tree
- leetcode-226-Invert Binary Tree
- leetcode 226 :Invert Binary Tree
- mac idea15 maven project 导入无反应
- Metron学习8_使用Metron安装Elasticsearch后,启动时No interface named 'eth1' found报错
- PHP SOCKET编程
- lintcode,排序列表转换为二分查找树
- Redux中间件在React和React-Native项目架构中的应用实践
- LeetCode #226 - Invert Binary Tree - Easy
- find grep sed 实现批量搜索文件,并替换字符串
- JAVA远程连接linux服务器读取文件(JSch)
- 利用Application 存储全变量
- springboot CGLib 方式实现AOP代理问题
- 常用的复用方法
- JSTL标签库
- Hibernate对象的三种状态
- spring annotation 注入static 属性