0%

102.二叉树的层序遍历

1. queue实现层次遍历

时间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
33
34
35
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int>> ans;

if (root != nullptr)
q.push(root);
while (!q.empty()) {
vector<int> sub;
int qsz = q.size();
while (qsz--) {
TreeNode* temp = q.front();
q.pop();
sub.push_back(temp->val);
if (temp->left != nullptr)
q.push(temp->left);
if (temp->right != nullptr)
q.push(temp->right);
}
ans.push_back(sub);
}

return ans;
}
};