mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
22 lines
676 B
Markdown
22 lines
676 B
Markdown
![]() |
# [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;
|
||
|
}
|
||
|
};
|
||
|
```
|