《剑指offer》:[23]从上往下打印二叉树

题目:从上往下打印二叉树
此题实质是考察树的遍历算法,只是这种遍历不是我们熟悉的前、中、后序遍历,而是我们的层次遍历。其实也很简单。分析如下:





   按层打印毫无疑问,我们需要从根节点开始,然后依次打印其子节点,为了能保证能打印其子节点,我们应该先保存其两个子节点。如上图先打印根结点8,然后保存其
左右结点4,12;然后再打印4,接着将3,6结点依次放入容器中;接着结点12,依次往下...很明显这是一个队列结构。所以我们可以借助一个队列来完成。
其实现代码如下:
#include <iostream>
#include <deque>
#include <queue>
using namespace std;
struct BinaryTree
{
	int data;
	BinaryTree *pLeft;
	BinaryTree *pRight;
};
BinaryTree *pRoot1=NULL;
deque<BinaryTree*> d1;
int arr[7]={8,4,12,3,6,10,14};
void InsertTree(BinaryTree *root,int data);
void CreateTree(BinaryTree **root,int *array,int length);
void PrintFronTopToBottom(BinaryTree *root);
void InsertTree(BinaryTree *root,int data)
{
	if(root->data > data)
	{
		if(NULL==root->pLeft)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=data;
			pNode->pLeft=pNode->pRight=NULL;
			root->pLeft=pNode;
		}
		else
			InsertTree(root->pLeft,data);
	}
	else
	{
		if(NULL==root->pRight)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=data;
			pNode->pLeft=pNode->pRight=NULL;
			root->pRight=pNode;
		}
		else
		{
			InsertTree(root->pRight,data);
		}
	}
}
void CreateTree(BinaryTree **root,int *array,int length)
{
	for(int i=0;i<length;i++)
	{
		if(NULL==*root)
		{
			BinaryTree *pNode=new BinaryTree;
			pNode->data=arr[i];
			pNode->pLeft=pNode->pRight=NULL;
			*root=pNode;
		}
		else
			InsertTree(*root,arr[i]);
	}
}
void PrintFronTopToBottom(BinaryTree *root)
{
	if(!root)
		return;
	BinaryTree *temp=root;
	d1.push_back(root);
	while(d1.size())
	{
		temp=d1.front();
		d1.pop_front();
		cout<<temp->data<<" ";
		if(temp->pLeft)
			d1.push_back(temp->pLeft);
		if(temp->pRight)
			d1.push_back(temp->pRight);
	}
}
int main()
{
	CreateTree(&pRoot1,arr,7);
	PrintFronTopToBottom(pRoot1);
	//PreOrder(pRoot1);
	cout<<endl;
	system("pause");
	return 0;
}

运行结果:


   小结:不管是树的层次遍历,还是广度优先遍历一个图或者是树,都要用到队列,第一步将起始结点放入队列中,然后每一次从队列的头部取出一个结点,遍历这个结点之后把它能到达的结点都依次放入队列。重复这个过程,知道队列里的结点全部遍历完为止。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值