花絮
二叉树的反转引发的血案
使用 macOS 的朋友大部分都用过 Homebrew。2015年,Homebrew 的作者 Max Howell 在 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.
意思就是,我们90%的工程师都用你写的软件(Google 有多爱 Apple),但你居然不能在白板上写出反转二叉树的代码,所以,滚吧。
这个是 Max Howell在面试Google没有做出二叉树的反转引发的小故事。
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树:
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树:
8
/ \
10 6
/ \ / \
11 9 7 5
解题思路
很容易想到递归思想(不太容易)。
考虑一个根节点为node二叉树,如果其为空,则直接返回;否则,将其左右子树分别镜像,然后交换其左右孩子节点即可。
AC代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(!pRoot)
return;
Mirror(pRoot->left); //将左子树进行镜像
Mirror(pRoot->right); //将右子树进行镜像
swap(pRoot->left, pRoot->right); //交换当前节点的左右孩子节点
return;
}
};