Skip to content

Commit fd6044f

Browse files
committed
update 226
1 parent 3b6d59d commit fd6044f

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

solutions/226. Invert Binary Tree.md

+34-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
# [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)
22
# 思路
3-
翻转二叉树。
3+
翻转二叉树。
4+
5+
## 思路一
46
递归算法的话很简单:
57
* 若为空树则返回空即可。
68
* 令左子树指向翻转后的右子树,将右子树指向翻转后的左子树。
79

8-
非递归算法的话用先方向层序遍历(从右到左从上到下),然后再正常层序重新赋值即可。
10+
## 思路二
11+
12+
非递归算法的话类似层序遍历,因为我们要交换所有节点的左右孩子,所以我们用一个队列存放左右孩子还未交换的节点,初始为root。然后开始循环直到队列为空:出队首节点然后交换其左右孩子,然后再将其左右孩子入队(如果不为空的话)。
13+
14+
两个思路都相当于遍历二叉树,所以时间复杂度均为O(n),空间复杂度也均为O(n)。
15+
916
# C++
17+
18+
## 思路一
1019
``` C++
1120
class Solution {
1221
public:
@@ -19,3 +28,26 @@ public:
1928
}
2029
};
2130
```
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+
```

0 commit comments

Comments
 (0)