题解 | #求二叉树的层序遍历# | C++
求二叉树的层序遍历
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) {} * }; */ #include <vector> #include <queue> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrder(TreeNode* root) { vector<vector<int>> ans; if (root == nullptr) return ans; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int n = q.size(); vector<int> item; while (n-- >= 1) { auto f = q.front(); item.push_back(f->val); if (f->left) q.push(f->left); if (f->right) q.push(f->right); q.pop(); } ans.push_back(std::move(item)); } return ans; } };