题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://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) {
vector<vector<int> >res;
if(root==nullptr)return res;
queue<TreeNode *>q;
q.push(root);
TreeNode *cur;
while(!q.empty()){
vector<int> row;
int n=q.size();
for(int i=0;i<n;++i){
cur=q.front();
q.pop();
row.push_back(cur->val);
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
res.push_back(row);
}
return res;
// write code here
}
};
/**
* 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) {
vector<vector<int> >res;
if(root==nullptr)return res;
queue<TreeNode *>q;
q.push(root);
TreeNode *cur;
while(!q.empty()){
vector<int> row;
int n=q.size();
for(int i=0;i<n;++i){
cur=q.front();
q.pop();
row.push_back(cur->val);
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
res.push_back(row);
}
return res;
// write code here
}
};

曼迪匹艾公司福利 138人发布