題目描述:從上到下按層打印二叉樹,同一層的結點按從左到右的順序打印,每一層打印到一行,例如:
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;
}
}
}