力扣

    image.png

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. vector<vector<int>> levelOrder(TreeNode* root) {
    15. vector<vector<int>> ans;
    16. if(root == NULL){
    17. return ans;
    18. }
    19. queue<TreeNode*> q;
    20. q.push(root);
    21. while(!q.empty()){
    22. int size = q.size();
    23. ans.push_back(vector<int>());
    24. for(int i = 0;i < size;i++){
    25. TreeNode* node = q.front();
    26. q.pop();
    27. ans.back().push_back(node->val);
    28. if(node->left != NULL){
    29. q.push(node->left);
    30. }
    31. if(node->right != NULL){
    32. q.push(node->right);
    33. }
    34. }
    35. }
    36. return ans;
    37. }
    38. };