File tree 1 file changed +34
-2
lines changed
1 file changed +34
-2
lines changed Original file line number Diff line number Diff line change 1
1
# [ 226. Invert Binary Tree] ( https://leetcode.com/problems/invert-binary-tree/description/ )
2
2
# 思路
3
- 翻转二叉树。
3
+ 翻转二叉树。
4
+
5
+ ## 思路一
4
6
递归算法的话很简单:
5
7
* 若为空树则返回空即可。
6
8
* 令左子树指向翻转后的右子树,将右子树指向翻转后的左子树。
7
9
8
- 非递归算法的话用先方向层序遍历(从右到左从上到下),然后再正常层序重新赋值即可。
10
+ ## 思路二
11
+
12
+ 非递归算法的话类似层序遍历,因为我们要交换所有节点的左右孩子,所以我们用一个队列存放左右孩子还未交换的节点,初始为root。然后开始循环直到队列为空:出队首节点然后交换其左右孩子,然后再将其左右孩子入队(如果不为空的话)。
13
+
14
+ 两个思路都相当于遍历二叉树,所以时间复杂度均为O(n),空间复杂度也均为O(n)。
15
+
9
16
# C++
17
+
18
+ ## 思路一
10
19
``` C++
11
20
class Solution {
12
21
public:
@@ -19,3 +28,26 @@ public:
19
28
}
20
29
};
21
30
```
31
+
32
+ ## 思路二
33
+ ``` C++
34
+ class Solution {
35
+ public:
36
+ TreeNode* invertTree(TreeNode* root) {
37
+ if(root == NULL) return NULL;
38
+ queue<TreeNode *>q;
39
+ q.push(root);
40
+
41
+ TreeNode *p = NULL, *tmp = NULL;
42
+ while(!q.empty()){
43
+ p = q.front(); q.pop();
44
+ tmp = p -> left;
45
+ p -> left = p -> right;
46
+ p -> right = tmp;
47
+ if(p -> left) q.push(p -> left);
48
+ if(p -> right) q.push(p -> right);
49
+ }
50
+ return root;
51
+ }
52
+ };
53
+ ```
You can’t perform that action at this time.
0 commit comments