题目描述:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行,例如:
void Print()
{
if (_root == NULL)
return;
queue<Node*>q;
q.push(_root);
int NextLevel = 0; //下一行结点的个数
int CurLevel = 1; //当前行结点的个数
while (!q.empty())
{
Node* front = q.front();
cout << front->_value << " ";
q.pop();
CurLevel--;
if (front->_left)
{
q.push(front->_left);
NextLevel++;
}
if (front->_right)
{
q.push(front->_right);
NextLevel++;
}
if (CurLevel == 0) //说明该行的结点都已被打印
{
printf("\n");
CurLevel = NextLevel;
NextLevel = 0;
}
}
}