题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
queue<TreeNode*> q1;
queue<TreeNode*> q2;
vector<int> qr;
vector<vector<int>> res;
if(root != nullptr)
{
q1.push(root);
// res.push_back(vector<int>(1,root->val));
}
while(!q1.empty()){
TreeNode* f = q1.front();
qr.push_back(f->val);
q1.pop();
if(f->left != nullptr) {
q2.push(f->left);
}
if(f->right != nullptr){
q2.push(f->right);
}
if(q1.empty()){
q1.swap(q2);
res.push_back(qr);
qr.clear();
}
}
return res;
}
};
查看6道真题和解析