题目来源:LeetCode: 226. Invert Binary Tree
趣闻: 据说homebrew的作者Max Howell去Google面试,被要求在白板上手写出二叉树翻转的代码,由于没有写出来被鄙视了。后经Twitter传为笑谈。
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.
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
思路
- 二叉树,递归调用,翻转操作为左右子节点交换位置。时间复杂度O(n)
源码
1 | /** |
运行结果:
68 / 68 test cases passed.
Status: Accepted
Runtime: 0 ms
Submitted: 0 minutes agoYou are here! Your runtime beats 0.76% of csubmissions.
PS: I have no idea why 0ms only beats 0.76% of submissions!?
总结
- 熟悉和理解C的指针操作是该题优势。
- 增加子节点NULL判断,减少非必要的循环操作。
- 掌握二叉树的操作特点,白板写出也是可以做到的。