Invert Binary Tree
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.
struct TreeNode* invertTree(struct TreeNode* root) {
struct TreeNode *tmp1;
if(!root) return root;
if(!root->left && !root->right) return root;
if( root->left && !root->right)
{
root->right=invertTree(root->left);;
root->left = NULL;
}
else if( !root->left && root->right)
{
root->left=invertTree(root->right);
root->right = NULL;
}
else if( root->left && root->right)
{
tmp1 = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tmp1);
}
return root;
}
递归交换左右子树,注意空的情况。