二叉树的层序遍历
    题目链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
    图片.png

    思路:经典字节题,本身不难,注意一个小trick在于每层结束遍历的终止条件可以通过当前队列中的元素个数来确定,注意不能把q.size()写到循环条件里。

    参考代码:

    1. class Solution {
    2. public:
    3. vector<vector<int>> levelOrder(TreeNode* root) {
    4. vector<vector<int>> res;
    5. if (!root) {
    6. return res;
    7. }
    8. queue<TreeNode*> q;
    9. q.push(root);
    10. vector<int> subRes;
    11. while (!q.empty()) {
    12. int size = q.size();
    13. for (int i = 0; i < size; ++i) {
    14. TreeNode* curr = q.front();
    15. q.pop();
    16. subRes.push_back(curr->val);
    17. if (curr->left) {
    18. q.push(curr->left);
    19. }
    20. if (curr->right) {
    21. q.push(curr->right);
    22. }
    23. }
    24. res.push_back(subRes);
    25. subRes.clear();
    26. }
    27. return res;
    28. }
    29. };