struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode():val(0),left(nullptr),right(nullptr){}
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
TreeNode(int x,TreeNode *left, TreeNode *right):val(x),left(left),right(right){}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> ret;
if(root == nullptr) return ret;
queue<TreeNode *> que;//定义一个队列存放结点
que.push(root);
while(!que.empty()) {
int curLevelSize = que.size();//队列中每次存放的都是某一层元素的总个数
ret.emplace_back(vector<int>());
for(int i = 0;i<curLevelSize;i++) {
TreeNode *node = que.front();//取出队首元素
que.pop();
ret.back().push_back(node->val);
if(node->left) que.push(node->left);//将当前结点的左子树和右子树入队,作为下一层遍历的元素
if(node->right) que.push(node->right);
}
}
return ret;
}
};
LeetCode #102. 二叉树的层序遍历 题解 C/C++
最新推荐文章于 2022-04-05 23:07:29 发布