102.二叉树的层序遍历
- 题目:
1 | 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 |
- 思路:
迭代:由于层序遍历需要从左向右遍历每一层,比较容易想到的是把每个结点的左右子节点按顺序插入队列,再按照队列顺序遍历。问题是怎么换行,可以用两个队列交替使用,每次遍历一个,向另外一个插入,这样遍历结束一个队列意味着本层结束。结束条件为两个队列都为空。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 /**
* 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:
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root) return {};
queue<TreeNode*> q1, q2;
vector<vector<int>> ans;
vector<int> tmp;
q1.push(root);
while(!(q1.empty() && q2.empty())){
while(!q1.empty()){
if(q1.front()){
tmp.emplace_back(q1.front()->val);
q2.push(q1.front()->left);
q2.push(q1.front()->right);
}
q1.pop();
}
if(!tmp.empty()) ans.emplace_back(tmp);
tmp.clear();
while(!q2.empty()){
if(q2.front()){
tmp.emplace_back(q2.front()->val);
q1.push(q2.front()->left);
q1.push(q2.front()->right);
}
q2.pop();
}
if(!tmp.empty()) ans.emplace_back(tmp);
tmp.clear();
}
return ans;
}
};调试中没考虑到的问题:空的层不插入结果容器。
时间复杂度:每个节点访问一次,
O(N)
;空间复杂度:两个队列加答案容器:O(N)
。递归:我认为这道题不适合递归,因为输入为一个节点指针,无法知道本层的其他节点。
我错了,可以用递归,不过递归不是调用自身,是另外写一个递归函数。
思路:
递归函数实现的功能:层序遍历二叉树(的一部分);需要的参数:本层所有节点
终止条件:根节点为空
递推关系:遍历一层,输出,层序遍历树的剩余部分。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 /**
* 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:
vector<vector<int>> levelOrder(TreeNode* root) {
lvlOdr({root});
return ans;
}
private:
void lvlOdr(vector<TreeNode*> curLevel){
if(curLevel.empty()) return;
vector<TreeNode*> nextLevel;
vector<int> tmp;
for(const auto& ptr:curLevel){
if(ptr){
tmp.emplace_back(ptr->val);
nextLevel.emplace_back(ptr->left);
nextLevel.emplace_back(ptr->right);
}
}
if(!tmp.empty()) ans.emplace_back(tmp);
lvlOdr(nextLevel);
}
vector<vector<int>> ans;
};时间复杂度:
O(N)
,空间复杂度:O(N)