102. 二叉树的层次遍历
题目
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root==nullptr)
return res;
list<TreeNode*> que;
que.push_back(root);
int currentLength=1;
int nextLength=0;
while(que.empty()==false)
{
vector<int> vec;
while(currentLength>0)
{
auto ptr=que.front();
que.pop_front();
currentLength--;
vec.push_back(ptr->val);
if(ptr->left)
{
que.push_back(ptr->left);
nextLength++;
}
if(ptr->right)
{
que.push_back(ptr->right);
nextLength++;
}
}
res.push_back(vec);
currentLength=nextLength;
nextLength=0;
}
return res;
}
};
思路
用一个辅助vector以及两个变量currentLength和nextLength表示当前层的节点个数和下一层的节点个数,每次取出一个当前层结点时,currentLength--,把它的非空孩子加入vector,nextLength++。直到currentLength==0则表示当前层遍历完,使得currentLength=nextLength;
https://github.com/li-zheng-hao