《劍指offer》:[60]把二叉樹打印成多行

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

例如,圖(1)中二叉樹以及打印結果爲:


這個題其實很簡單,我們只需要設置兩個變量就可以搞定。一個變量表示當前層中還沒有打印的結點數,另一個變量表示下一層結點的數目。
具體實現代碼如下:
#include <iostream>
#include <queue>
using namespace std;
struct BinaryTree
{
	int data;
	BinaryTree *pLeft;
	BinaryTree *pRight;
};
BinaryTree *pRoot1=NULL;
queue<BinaryTree *> node;
void CreateTree(BinaryTree *&root)
{
	int data;
	cin>>data;
	if(0==data)
		root=NULL;
	else
	{
		root=new BinaryTree;
		root->data=data;
		CreateTree(root->pLeft);
		CreateTree(root->pRight);
	}
}
void PrintTree(BinaryTree *root)
{
	if(NULL==root)
		return;
	node.push(root);
	int nextlevel=0;//下一層的結點數;
	int tobePrinted=1;//當前還有幾個結點;
	while(!node.empty())
	{
		BinaryTree *pNode=node.front();
		cout<<pNode->data<<" ";
		if(pNode->pLeft!=NULL)
		{
			node.push(pNode->pLeft);
			nextlevel++;
		}
		if(pNode->pRight!=NULL)
		{
			node.push(pNode->pRight);
			nextlevel++;
		}
		node.pop();//入隊列的速度比出隊列的要快;
		tobePrinted--;
		if(tobePrinted==0)
		{
			cout<<endl;//一行打印完了,所以換行;
			tobePrinted=nextlevel;
			nextlevel=0;
		}
	}
}
int main()
{
	CreateTree(pRoot1);
	cout<<"之字形打印如下:"<<endl;
	PrintTree(pRoot1);
	cout<<endl;
	system("pause");
	return 0;
}

運行結果如下:





發佈了250 篇原創文章 · 獲贊 191 · 訪問量 57萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章