题目1523:从上往下打印二叉树

明明PE,显示WA,郁闷。

层次遍历,利用队列,把根入队列

循环-》输出队首-》儿子入队列

over

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

typedef struct node
{
	int val;
	struct node *left;
	struct node *right;
	void setVal(int v)
	{
		this->val = v;
		left = right = NULL;
	}
}Tree;

void createTree(Tree tree[],int n)
{
	int val,childIndex;
	for(int i=0;i<n;++i)
	{
		scanf("%d",&val);
		tree[i].setVal(val);
	}
	for(int i=0;i<n;++i)
	{
		char ch[2];
		scanf("%s",ch);
		if(ch[0] == 'd')
		{
			scanf("%d",&childIndex);
			tree[i].left = &tree[childIndex-1];
			scanf("%d",&childIndex);
			tree[i].right = &tree[childIndex-1];
		}
		else if(ch[0] == 'l')
		{
			scanf("%d",&childIndex);
			tree[i].left = &tree[childIndex-1];
		}
		else if(ch[0] == 'r')
		{
			scanf("%d",&childIndex);
			tree[i].right = &tree[childIndex-1];
		}
	} 
}


void printTree(Tree *tree)
{
	queue<Tree *>qu;
	qu.push(tree);
	bool first = true;
	while(!qu.empty())
	{
		Tree *t = qu.front();
		qu.pop();
		if(first)
			printf("%d",t->val);
		else
			printf(" %d",t->val);
		first = false;
		if(t->left != NULL)
		{
			qu.push(t->left);
		}
		if(t->right != NULL)
		{
			qu.push(t->right);
		}
	}
}

int main()
{
	int n;
	while(scanf("%d",&n) != EOF)
	{
		Tree tree[1111];
		createTree(tree,n);
		printTree(tree);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值