Invert Binary Tree
来源:互联网 发布:mac版谷歌dhc插件下载 编辑:程序博客网 时间:2024/06/11 17:45
今天看到leetcode又更新了,先把easy题办了。不过没想到这道题有点来头,
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.
貌似是homebrem的作者去谷歌面试,然后被这道题难倒了,于是fuck off。谷歌就是牛,管你什么大牌什么软件明星,过不了我的槛就别进我的门。
其实这道题不难,不知道是不是面试者被谷歌吓到了,一看是自己不熟悉的然后又是谷歌出的以为很难,于是退缩了。估计回来后细细一想突然发觉很简单,顿感有一种被谷歌坑了的感觉,所以在推特上发了以上感慨。
说下自己思路:刚拿到一看也以为有难度,但一想既然是easy题肯定用不了多少行。最开始由传统思路肯定会想到一路遍历到左叶子然后一步步回退,那就要设两个指针另一个从root的右子树遍历,那有个问题就是如果不是对称的怎么办?既然从叶子开始不方便,那么就从根开始,直接在每一次中序遍历就交换左右节点。因为交换的是节点而不是节点中得值,所以相当于交换了整棵左右子树。这个理解很重要,因为按此流程递归下去就正是题目所要求的invert。如果是用交换值的方式,那么就要考虑左右位置对称的问题。
如下:
struct TreeNode* invertTree(struct TreeNode* root) { struct TreeNode *result = root; if (!result) return NULL; struct TreeNode *tl = result->left; struct TreeNode *tr = result->right; result->left = tr; result->right = tl; invertTree(result->left); invertTree(result->right); return result;}
0 0
- [leetcode] Invert Binary Tree
- [LeetCode]Invert Binary Tree
- Invert Binary Tree
- leetcode:Invert Binary Tree
- Invert Binary Tree
- LeetCode Invert Binary Tree
- 226Invert Binary Tree
- LeetCode | Invert Binary Tree
- leetcode--Invert Binary Tree
- [leetcode] Invert Binary Tree
- [LeetCode] Invert Binary Tree
- LeetCode Invert Binary Tree
- Invert Binary Tree
- leetcode : Invert Binary Tree
- 226Invert Binary Tree
- Invert Binary Tree
- [LeetCode] Invert Binary Tree
- [Leetcode]Invert Binary Tree
- 【数据结构】跳跃列表 SkipList
- 时间格式化函数strftime
- Codeforces #186(div 2)D. Ilya and Roads
- LCD12864液晶使用-ST7920
- NIO系列6:流行 NIO Framework netty 和 mina 性能测评与分析
- Invert Binary Tree
- 二分+贪心
- OpenVPN下载、安装、配置及使用详解
- C#类的理解
- 用presentingViewController实现左右切换视图
- 数据库基线
- 针对cocos2d图片资源自定义加密的解密
- Android Intent-Filter中的action
- PowerDesigner列名、注释内容互换