PAT--Tree Traversals Again (25)--找規律。。

題目地址:http://www.patest.cn/contests/mooc-ds2015spring/03-樹2

這道題陳越老師的解法太讚了。

push進去的數字序列就是前序,而pop()出來的序列就是後序,so...剩下的我就不說了,

前序中序求後續是很經典的遞歸,如果不清楚可以百度一下~

我這道題的解法是通過找規律建樹,囧。

規律就是:

在push時,看一看上一個操作是不是push,如果是,則插到上一個數左邊。

如果不是,則插入到上一次pop()出來的右邊。

#include<stdio.h>
#include<stack>
using namespace std;

typedef struct node{
	int left,right;
	int x;
	bool pop;
}Tree;
Tree tree[31];
stack<int> S;

int coun;
void postOrder(int root){
	if(tree[root].left!=-1)
		postOrder(tree[root].left);
	if(tree[root].right!=-1)
		postOrder(tree[root].right);
	if(coun==0){
		printf("%d",tree[root].x);
		coun++;
	}
	else{
		printf(" %d",tree[root].x);
		coun++;
	}
}


int main(){
	coun=0;
	bool push = true; 
	char str[10];
	int i,N,x,out,root;
	for(i=0;i<31;i++){
		tree[i].x=i;
		tree[i].left=tree[i].right=-1;
		tree[i].pop=false;
	}

	scanf("%d",&N);
	//gets(str);
	//主代碼:
	for(i=0;i<2*N;i++){
		scanf("%s",str);
		if(i==0){
			scanf("%d",&x);
			root=x;
			S.push(x);
			continue;
		}
		if(str[1]=='u'){
			scanf("%d",&x);
			if(push){
				tree[S.top()].left=x;
				S.push(x);
				//“上一次”操作的是push
				push=true;
			}
			else{
				tree[out].right=x;
				S.push(x);
				//“上一次”操作的是push
				push=true;
			}
		}
		else if(str[1]=='o'){
			out=S.top();
			S.pop();
			//上一次操作的是pop();
			push=false;
		}
	}
	postOrder(root);

	return 0;
}

			
			




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章