Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree ​​​[3,9,20,null,null,15,7]​​,

3
/ \
9 20
/ \
15 7

 

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]

题解:

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
if (root == NULL) {
return {};
}
q.push(root);
int cnt = 1;
vector<int> v;
vector<vector<int>> res;
while(q.empty() == false) {
if (cnt >= 0) {
cnt--;
TreeNode *t = q.front();
q.pop();
v.push_back(t->val);
if (t->left != NULL) {
q.push(t->left);
}
if (t->right != NULL) {
q.push(t->right);
}
}
if (cnt == 0) {
res.push_back(v);
v.clear();
cnt = q.size();
}
}
return res;
}
};