目录
一、题目
二、代码
一、题目
102. 二叉树的层序遍历 - 力扣(LeetCode)
二、代码
- 主要应用到了两个队列,一个队列存放数据,一个队列存放对应所在的第几层
/**
* Definition for a binary tree node.
* 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:
int Number_of_layers(TreeNode* root)//计算二叉树的层数
{
if(root == nullptr)
{
return 0;
}
int left = Number_of_layers(root->left);
int right = Number_of_layers(root->right);
return left>right?left+1:right+1;
}
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>d1;//存放结点
queue<int>d2;//存放对应在第几层
int Number_layers = Number_of_layers(root);
vector<vector<int>>data(Number_layers);//提前指定二维vector的行数
if(root == nullptr)
return data;
d1.push(root);
d2.push(0);
while(!d1.empty())//层序遍历
{
TreeNode*front = d1.front();
int i = d2.front();
data[i].push_back(front->val);
d1.pop();
d2.pop();
if(front->left!=nullptr)
{
d1.push(front->left);
d2.push(i+1);
}
if(front->right!=nullptr)
{
d1.push(front->right);
d2.push(i+1);
}
}
return data;
}
};