PTA treetraveragain

思想很简单,输入的字符串序列是一个递归的

//左右链表示

#include <iostream>

using namespace std;
#define N 30
char Data[2*N][10];
int counter;
typedef int Elemtype_Tree;
struct Tree_Data
{
	Tree_Data* lchild;
	Tree_Data* rchild;
	Elemtype_Tree data;
	int Status;  //保留断点
	Tree_Data* temp;

};
typedef Tree_Data* BTREE;
typedef BTREE ElementType;
int temp[2 * N];

void PostOrder(int temp[2 * N],BTREE BT)
{
	if (BT != NULL)
	{
		
		PostOrder(temp,BT->lchild);
		PostOrder(temp,BT->rchild);
		temp[counter++] = BT->data;
	}


}



int SearchPop(int n, int from)  //n是树中结点个数,from是Push所在结点对应的数组行下标从0开始
{

	int push = 0;
	int pop = 0;
	int i;
	for ( i = from+1; i < 2*n-1; i++)
	{
		if (Data[i][1] == 'u') push++;
		else pop++;
		if (pop > push) break;
	}
	return i;
}

int chartoint(char *p)
{
	if (*(p + 1) == 0) return (*p) - '0';
	return (*p - '0') * 10 + (*(p + 1) - '0');


}


BTREE Creat(char Data[2 * N][10],int From,int To,int n)  //生成二叉树
{ 
	if (To > 2*n - 1 || From < 0 || To <= From||n == 0) return NULL;
	BTREE root = (BTREE)calloc(1, sizeof(Tree_Data));
	char* p = &Data[From][5];
	root->data = chartoint(p);
	int q = SearchPop(n, From);
	if (From + 1 == q) root->lchild = NULL;
	else root->lchild = Creat(Data, From+1,q-1,n);
	if(q==To) root->rchild = NULL;
	else root->rchild = Creat(Data, q+1, To,n);
	return root;
		
}


int main()
{
	for (int i = 0; i < 60; i++)
	{
		for (int j = 0; j < 10; j++)
			Data[i][j] = 0;
	}
	int n;
	cin >> n;
	getchar();
	for (int i = 0; i < 2*n; i++)
	{
		//scanf_s("%[^\n]", Data[i],10);
		int j = 0;
		while (1)
		{
			char temp = getchar();
			if (temp == '\n') break;
			else Data[i][j++] = temp;
		}


		
	}
	
	BTREE root = Creat(Data, 0, 2 * n-1, n);
	PostOrder(temp,root);
	for (int i = 0; i < counter; i++)
	{
		
		if (i == counter - 1) printf("%d", temp[i]);
		else printf("%d ", temp[i]);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值