题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int> > ret;
queue<TreeNode*> q;
if(root == nullptr) return ret;
q.push(root);
while(!q.empty())
{
int n = q.size();
vector<int> v;
for(int i=0;i<n;++i)
{
TreeNode* temp=q.front();
q.pop();
v.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
ret.push_back(v);
}
return ret;
}
};
SHEIN希音公司福利 318人发布
查看2道真题和解析