HDU 3791 二叉搜索树

时间:2023-03-08 19:33:15

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2148    Accepted Submission(s): 957

Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
0
Sample Output
YES
NO
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string.h>
using namespace std; typedef struct node
{
char data;
node *lchild;
node *rchild;
node()
{
lchild = rchild = NULL;
}
}TreeNode; void CreateTree(TreeNode *&pRoot, char ch)
{
if (pRoot == NULL)
{
pRoot = new TreeNode;
pRoot->data = ch;
}
else
{
if (ch > pRoot->data)
{
CreateTree(pRoot->rchild, ch);
}
else
{
CreateTree(pRoot->lchild, ch);
}
}
} bool IsEqual(TreeNode *pRoot1, TreeNode *pRoot2)
{
if (pRoot1 != NULL && pRoot2 != NULL)
{
if (pRoot1->data != pRoot2->data)
{
return false;
}
if (IsEqual(pRoot1->lchild, pRoot2->lchild) && IsEqual(pRoot1->rchild, pRoot2->rchild))
{
return true;
}
}
else
{
if (pRoot1 == NULL && pRoot2 == NULL)
{
return true;
}
}
return false;
} void DeleteTree(TreeNode *pRoot)
{
if (pRoot != NULL)
{
DeleteTree(pRoot->lchild);
DeleteTree(pRoot->rchild);
}
delete pRoot;
} int main()
{
int n;
char str[];
while(scanf("%d", &n) != EOF && n != )
{
scanf("%s", str);
TreeNode *pRoot = NULL;
for (int i = ; i < strlen(str); i++)
{
CreateTree(pRoot, str[i]);
}
for (int i = ; i < n; i++)
{
scanf("%s", str);
TreeNode *pRoot1 = NULL;
for (int j = ; j < strlen(str); j++)
{
CreateTree(pRoot1, str[j]);
}
if (IsEqual(pRoot, pRoot1))
{
printf("YES\n");
}
else
{
printf("NO\n");
}
DeleteTree(pRoot1);
}
DeleteTree(pRoot);
}
return ;
}