mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 226. Invert Binary Tree.md
This commit is contained in:
parent
22a9600522
commit
25aa7bd049
21
226. Invert Binary Tree.md
Normal file
21
226. Invert Binary Tree.md
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)
|
||||||
|
# 思路
|
||||||
|
翻转二叉树。
|
||||||
|
递归算法的话很简单:
|
||||||
|
* 若为空树则返回空即可。
|
||||||
|
* 令左子树指向翻转后的右子树,将右子树指向翻转后的左子树。
|
||||||
|
|
||||||
|
非递归算法的话用先方向层序遍历(从右到左从上到下),然后再正常层序重新赋值即可。
|
||||||
|
# C++
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
TreeNode* invertTree(TreeNode* root) {
|
||||||
|
if(root == NULL) return NULL;
|
||||||
|
TreeNode *tmp = root -> left;
|
||||||
|
root -> left = invertTree(root -> right);
|
||||||
|
root -> right = invertTree(tmp);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user