【PAT 甲级】A1020 Tree Traversals(25分)

一遍AC,中序+后序=>层次
简单模拟了一下构造以及遍历的过程就可以了。
不过我记得在学DS的时候,好像看见过同学用简单的逻辑结构就直接能求出来…唉…不管啦哈哈

#include <bits/stdc++.h>
using namespace std;
struct node
{
	int value;
	node* left;
	node* right;
};
int post[31];
int in[31];
node* create(int plo,int phi,int ilo,int ihi)
{
	int i,numLeft;
	if(plo>phi) return NULL;
	node* nd=new node;
	for(i=ilo;i<=ihi;i++)
	{
		if(in[i] == post[phi]) break;	//find the root
	}
	numLeft=i-ilo-1;						//the number of the nodes in the left tree
	nd->value=post[phi];
	nd->left=create(plo,plo+numLeft,ilo,i-1);
	nd->right=create(plo+numLeft+1,phi-1,i+1,ihi);
	return nd;
}
int main(void)
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	scanf("%d",&post[i]);
	for(int i=0;i<n;i++)
	scanf("%d",&in[i]);
	node* root=create(0,n-1,0,n-1);
	node* nd=new node;
	queue<node*> q;
	q.push(root);
	while(!q.empty())
	{
		nd=q.front();
		q.pop();
		printf("%d",nd->value);
		if(nd->left) q.push(nd->left);
		if(nd->right) q.push(nd->right);
		if(!q.empty()) printf(" ");
	}
}
发布了15 篇原创文章 · 获赞 1 · 访问量 177

猜你喜欢

转载自blog.csdn.net/weixin_42278063/article/details/104600238