Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
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的作者去Google面试就被问了这道题,结果他想了半天 没 想 出 来!哈哈哈
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL||root->left==NULL&&root->right==NULL){
return root;
}
TreeNode* temp=root->left;
root->left=root->right;
root->right=temp;
if(root->left){
invertTree(root->left);
}
if(root->right){
invertTree(root->right);
}
return root;
}
};