判断两序列是否为同一二叉搜索树

#include
#include
using namespace std;
struct node
{
	node *lchild;
	node *rchild;
	int c;
}tree[100];
int loc = 0;
char str1[30], str2[30];
int size1, size2;
char *str;
int *daxiao;
node *creat()
{
	tree[loc].lchild = tree[loc].rchild = NULL;
	return &tree[loc++];
}
 void xianxu(node *t)
{
	str[(*daxiao)++] = t->c + '0';
	if (t->lchild != NULL)
		xianxu(t->lchild);
	if (t->rchild != NULL)
		xianxu(t->rchild);
}
void zhongxu(node *t)
{
	if (t->lchild != NULL)
		xianxu(t->lchild);
	str[(*daxiao)++] = t->c + '0';
	if (t->rchild != NULL)
		xianxu(t->rchild);
}
node *insert(node *t,int x)
{
	if (t == NULL)
	{
		t = creat();
		t->c = x;
		return t;
	}
	else if (x < t->c)
		t->lchild = insert(t->lchild, x);
	else if (x > t->c)
		t->rchild = insert(t->rchild, x);
	return t;
}
int main()
{
	int n;
	while (scanf("%d", &n) != EOF && n != 0)
	{
		node *t=NULL;
		char temp[30];
		scanf("%s", temp);
		for (int i = 0; temp[i] != 0; i++)
			t= insert(t, temp[i] - '0');
		int size1 = 0;
		str = str1;
		daxiao = &size1;
		xianxu(t);
		zhongxu(t);
		str1[size1] = 0;
		for (int i = 0; i < n; i++)
		{
			node *T=NULL;
			scanf("%s", temp);
			for (int i = 0; temp[i] != 0; i++)
				T= insert(T, temp[i] - '0');
			int size2 = 0;
			daxiao = &size2;
			str = str2;
			xianxu(T);
			zhongxu(T);
			str2[size2] = 0;
			int jud = strcmp(str1, str2);
			if (jud != 0)
				printf("NO\n");
			else
				printf("YES\n");
		}
	}
	return 0;
}

使用的方法是使用序列构建二叉树然后比较两个树的先序遍历和中序遍历是否一致,若一致则两个是同一个树。

你可能感兴趣的:(判断两序列是否为同一二叉搜索树)