给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL){
return res;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int levelCurrentSize = q.size();
res.push_back(vector<int>());
for(int i =0;i<levelCurrentSize;i++){
TreeNode* cur = q.front();
q.pop();
res.back().push_back(cur->val);
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
}
return res;
}
};