方法:辅助队列

层序遍历本质就是广度优先搜索(BFS),通过构建辅助队列可以很好的得到二叉树的层序遍历。

时间复杂度:o(n)

空间复杂度:o(n)

class Solution {
  public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (root == nullptr)
            return res;

        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            vector<int> temp;
            int length = q.size();
            for (int i = 0; i < length; i++) {
                temp.push_back(q.front()->val);
                //结点不为空时才写入
                if (q.front()->left)
                    q.push(q.front()->left);
                if (q.front()->right)
                    q.push(q.front()->right);
                q.pop();
            }
            res.push_back(temp);
        }
        return res;
    }
};