把二叉樹打印成多行

題目描述:從上到下按層打印二叉樹,同一層的結點按從左到右的順序打印,每一層打印到一行,例如

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;
		}
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章