使用一个队列来存放每一层的结点,时间复杂度 O ( n ) O(n) O(n) ,空间复杂度 O ( n ) O(n) O(n) :
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> ans;
if(root == nullptr)
return ans;
q.push(root);
int flag = 1;
while(flag != 0) {
vector<int> tmp;
int ct = 0;
for(int i = 0; i < flag; ++i) {
tmp.push_back(q.front()->val);
if(q.front()->left) {
q.push(q.front()->left);
ct++;
}
if(q.front()->right) {
q.push(q.front()->right);
ct++;
}
q.pop();
}
flag = ct;
ans.push_back(tmp);
}
return ans;
}
};