本来是一题一题刷的,但是事出突然是吧,今天就做了LeetCode226。

事出有因,Max Howell被google拒了,然后在tweet发了一条状态:

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.

然后全世界的码农们都炸开锅了。于是LeetCode上也出了Invert Binary Tree。然后大家都非常愉快地开始刷这道把Max Howell拒了的题╮(╯▽╰)╭

这道题就是把一个树的左右子树反过来,就像这样:

        4                          4  
   /   \                      /   \  
     2     7       ----->       7     2  
  / \   / \                  / \   / \  
1   3 6   9                9   6 3   1  

然后解题应该就很简单了,特别考虑root=NULL的情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if(root == NULL) return root;
struct TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}