题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
模版
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int> > res;
if(!root) return res;
queue<TreeNode* > qu;
qu.push(root);
while(!qu.empty()){
int n = qu.size();
vector<int> vec;
while(n--){
TreeNode *node = qu.front();
qu.pop();
vec.emplace_back(node->val);
if(node->left) qu.push(node->left);
if(node->right) qu.push(node->right);
}
res.emplace_back(vec);
}
return res;
}
};