区别如下
分类 | 定义 | 加入 | 删除 | 判空 | 个数 | 头部 |
---|---|---|---|---|---|---|
队列 | queue<TreeNode*> q; | q.push(root); | q.pop(); | q.empty() | q.size() | q.front();q.back() |
栈 | stack< int > s; | s.push(item); | s.pop(); | s.empty() | s.size() | s.top(); |
优先队列 | priority_queue < int > q; | q.emplace(numi); 入队后会进行排序 | q.pop(); | q.push_front() q.push_back() | q.size() | q.top() |
deque | deque< int > q; | q.push_front(numi); q.push_back(numi); | q.pop_front(); q.pop_back(); | q.empty() | q.size() | q.front() q.back() |
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector <vector <int>> ret;
if(root == NULL) {
return ret;
}
queue<TreeNode*> q;
TreeNode* tmp;
q.push(root);
int count = 1;
while(!q.empty()) {
count = q.size();
ret.push_back(vector<int>());
for(int i = 0; i < count; i++) {
tmp = q.front();
ret.back().push_back(tmp->val);
q.pop();
if(tmp->left!=NULL) {
q.push(tmp->left);
}
if(tmp->right!=NULL) {
q.push(tmp->right);
}
}
}
return ret;
}
};