从上到下打印二叉树 II
又是知道用队列保存层次遍历,但是被如何分层卡住了 ,看了题解发现确实很秀,我一开始是不管是不是NULL都插入,然后用一个累加器计算当前位置是否需要分层,拉跨,其实只需维护两个变量thisline和nextline即可
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==NULL)
return res;
queue<TreeNode *> all;
all.push(root);
int thisline=1; //根节点只有一个
int nextline=0;
vector<int > row;
while(!all.empty())
{
TreeNode *temp=all.front();
all.pop();
row.push_back(temp->val);
thisline--;
if(temp->left!=NULL) //当下一层非NULL时累加下一层个数
{
all.push(temp->left);
nextline++;
}
if(temp->right!=NULL)
{
all.push(temp->right);
nextline++;
}
if(thisline==0) //更新层次
{
res.push_back(row);
thisline=nextline;
nextline=0;
row.clear();
}
}
return res;
}