【算法】输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印

题目:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

例如输入

      8
    /  \
   6    10
  /\     /\
5  7   9  11

输出8   6   10   5   7   9   11。

思路是遍历一个结点时,首先访问它,然后将它的左右子树放入队列中。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;

typedef struct node
{
	int key;
	struct node *pleft;
	struct node *pright; 
}Node;

int CreateTreeByInsertData(Node **p,int k)//理解为什么用二级指针
{
	if(*p==NULL)      
	{
		*p=(Node *)malloc(sizeof(Node));	
		(*p)->key=k; 
		(*p)->pleft=(*p)->pright=NULL;     
		return 1;
	}
	else if(k == (*p)->key)          
		return 0;
	else if(k < (*p)->key)           
		return CreateTreeByInsertData(&(*p)->pleft,k); 
	else
		return CreateTreeByInsertData(&(*p)->pright,k);  

}

void visitByLevel(Node *p)
{
	queue<Node*> myQueue;
	if(p == NULL)
		return;
	myQueue.push(p);
	while(!myQueue.empty())
	{
		Node *now = myQueue.front();
		myQueue.pop();
		printf("%d ",now->key);
		if(now->pleft) myQueue.push(now->pleft);
		if(now->pright) myQueue.push(now->pright);
	}
	printf("\n");
}


void ClearTree(Node** tree)//删除树的操作,在本题中不一定用的到
{
	if(*tree==NULL)return;
	ClearTree(&(*tree)->pleft);
	ClearTree(&(*tree)->pright);
	free(*tree);
	*tree=NULL;
}


int main()
{
	int i;
	Node *proot = NULL;
	
	int data[] = {8,6,10,5,7,9,11};

	//依次插入一些数据,创建一个二叉排序树
	for(i=0; i<sizeof(data)/sizeof(int); i++)
		CreateTreeByInsertData(&proot, data[i]);
	visitByLevel(proot);

	ClearTree(&proot);

	return 0; 
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值