给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
void handle_levelorder(queue<TreeNode *> &q,vector<vector<int>> &res){
//如果队列不等于空
vector<int> vi;
if(q.empty()==false){
vector<TreeNode*> vt;
while(q.empty()==false){
TreeNode * h=q.front();
q.pop();
vi.push_back(h->val);
//res.push_back(vi);
vt.push_back(h);
}
res.push_back(vi);
for(int i=0;i<vt.size();i++){
if(vt[i]->left!=NULL){
q.push(vt[i]->left);
}
if(vt[i]->right!=NULL){
q.push(vt[i]->right);
}
}
vt.clear();
handle_levelorder(q,res);
}
}
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> res;
queue<TreeNode *> q;
if(root==NULL){
return res;
}
else{
q.push(root);
handle_levelorder(q,res);
}
return res;
}
};