【LeetCode】226. Invert Binary Tree

Invert a binary tree.

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

to

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

Trivia:
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.

这是一个有趣的故事,Homebrew的作者Max Howell去Google面试,有一道面试题是在白板上写反转二叉树,Max Howell没写出来,被拒掉了。Max Howell回来后就在推特上发帖:"Google: 虽然我们(Google工程师)有90%都在用你写的软件,但你不能在白板上写反转二叉树,所以快滚吧!!"

递归交换左右子树即可。

代码

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==0) return 0;
        TreeNode* p = root->right;
        root->right = root->left;
        root->left = p;
        invertTree(root->right);
        invertTree(root->left);
        return root;
    }
};