从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

    示例:
    二叉树:[3,9,20,null,null,15,7],

    1. 3
    2. / \
    3. 9 20
    4. / \
    5. 15 7

    返回结果:

    1. [3,9,20,15,7]
    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    8. * };
    9. */
    10. class Solution {
    11. public:
    12. vector<int> levelOrder(TreeNode* root) {
    13. vector<int> res;
    14. if(root == NULL) return res;
    15. queue<TreeNode*> q;
    16. q.push(root);
    17. while(!q.empty()){
    18. TreeNode* cur = q.front();
    19. q.pop();
    20. res.push_back(cur->val);
    21. if(cur->left != NULL) q.push(cur->left);
    22. if(cur->right != NULL) q.push(cur->right);
    23. }
    24. return res;
    25. }
    26. };