PAT 1020. Tree Traversals (25)


题意:给出后序和中序遍历,求水平序列。

思路:

用递归做,注意root要事先建立。还有就是递归处的边界选择。

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<stack>
#include<vector>
#include<queue>
#include<string>
#include<map>
using namespace std;
#define INF 99999999
#define M 300
struct node
{
	int data;
	struct node *lchild,*rchild;
};
int posto[M],mido[M];

struct node* buildtree(int ml,int mr,int pl,int pr)
{
	int i=0;
	if(ml>mr || pl >pr)
		return NULL;
	int proot=posto[pr];
	for(i=ml;i<=mr;i++)
		if(mido[i]==proot)
		{
			break;
		}

	struct node *Node;
	Node = (struct node*)malloc(sizeof(struct node));
	Node->data=proot;
	Node->rchild = buildtree(i+1,mr,pr-1-(mr-i-1),pr-1);
	Node->lchild = buildtree(ml,i-1,pl,pl+(i-1-ml));
	return Node;
}

void levelprint(struct node *root)
{
	struct node *Node;
	vector<int> ans;
	queue<struct node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node = q.front();
		q.pop();
		ans.push_back(Node->data);
		if(Node->lchild != NULL)
			q.push(Node->lchild);
		if(Node->rchild !=NULL)
			q.push(Node->rchild);
	}
	int i;
	for(i=0;i<ans.size();i++)
	{
		printf("%d",ans[i]);
		if(i!=ans.size()-1)
			printf(" ");
		else printf("\n");
	}
}

//start  21:54
//end    22:25
int main(){	
	int i,n;	
	struct node *root;
	cin>>n;
	for(i=0;i<n;i++)
		scanf("%d",&posto[i]);
	for(i=0;i<n;i++)
		scanf("%d",&mido[i]);
	root = (struct node*)malloc(sizeof(struct node));
	root = buildtree(0,n-1,0,n-1);
	levelprint(root);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值