一开始确定层数的结点个数卡住了,好好反思!
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root) {
std::queue<TreeNode *> queue_;
std::vector<std::vector<int>> res;
if (root == nullptr) {
return res;
}
queue_.push(root);
while (!queue_.empty()) {
// 获取每一层结点个数
int size = queue_.size();
std::vector<int> tmp;
for (int i = 0; i < size; ++i) {
// 出队的同时孩子结点入队
TreeNode *ptr = queue_.front();
queue_.pop();
tmp.push_back(ptr->val);
if (ptr->left) {
queue_.push(ptr->left);
}
if (ptr->right) {
queue_.push(ptr->right);
}
}
// 保存每一层的结果
res.emplace_back(std::move(tmp));
}
return res;
}
};