[leetcode] 226. Invert Binary Tree 解题报告

题目链接:https://leetcode.com/problems/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.

思路:这题有个故事,说是Max Howell去google面试,Max Howell是很有名的软件HomeBrew的作者,然后面试官本想放水,出了一道最简单的题目,谁知大神根本没get到面试官的良苦用心,居然这么不给面子的没做出来!然后完了还在推特上吐槽,引发了各种讨论。在本题的讨论区里各种恶搞,来看有个:

[leetcode] 226. Invert Binary Tree 解题报告_第1张图片


如果你A了这题,你就已经超过了顶级的程序员。大笑

不管你信不信,反正我是信了。

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return NULL;
        TreeNode* tem = root->left;
        root->left = root->right;
        root->right = tem;
        invertTree(root->left);
        invertTree(root->right);
        
        return root;
    }
};










你可能感兴趣的:(LeetCode,算法,tree,二叉树,binary)