# Invert Binary Tree【226】

Datetime:2016-08-23 01:23:27         Topic: LeetCode          Share        Original >>

### 226. Invert Binary Tree

My Submissions

Total Accepted:  57653 Total Submissions:  136144 Difficulty:  Easy

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.

Subscribe to see which companies asked this question

Hide Tags
```/**
* 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 == NULL){
return NULL;
}else{
//这样做将：树的底层先被真正交换，然后其上一层才做反转
TreeNode* newleft = invertTree(root->right);
TreeNode* newright = invertTree(root->left);
root->left = newleft;
root->right = newright;
return root;
}
}
};```

【1】博客地址，http://www.cnblogs.com/ganganloveu/p/4640933.html