给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
您在真实的面试中是否遇到过这个题?样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
返回它的层次遍历为:
[
[3],
[9,20],
[15,7]
]
挑战
只使用一个队列去实现它
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int> > ret;
if(!root)
return ret;
queue<TreeNode*> que;
que.push(root);
int len=1;
while(!que.empty()){
vector<int> base;
len=que.size(); //记录该层节点的总个数
while(len--){ //循环的目的是将该层的所有节点出队,并且把它们的孩子全部压入队列中
TreeNode *tmp=que.front();
base.push_back(tmp->val); //该层节点的值放入数组中
que.pop();
if(tmp->left)
que.push(tmp->left);
if(tmp->right)
que.push(tmp->right);
}
ret.push_back(base);
}
return ret;
}
};