题解 | #牛群分层排列#
牛群分层排列
https://www.nowcoder.com/practice/7e98027a60424c9ba88d9c4c0506ede4
知识点:
二叉树/层序遍历/队列
分析:
使用队列辅助进行层序遍历
将每一层的装入string对象中
编程语言:
C++
完整代码:
vector<string> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<string> res;
if(root == nullptr) return res;
q.push(root);
while(!q.empty()){
int size_ = q.size();
string path = "";
while(size_ --){
TreeNode* tmp = q.front();q.pop();
path += to_string(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
res.push_back(path);
}
return res;
}
