您的位置:首页 > 其它

HDU 3791 二叉搜索树

2013-08-15 14:13 344 查看

二叉搜索树

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


[align=left]Problem Description[/align]
判断两序列是否为同一二叉搜索树序列

[align=left]Input[/align]
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

[align=left]Output[/align]
如果序列相同则输出YES,否则输出NO

[align=left]Sample Input[/align]

2
567432

543267
576342
0

[align=left]Sample Output[/align]

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[15];
while(scanf("%d", &n) != EOF && n != 0)
{
scanf("%s", str);
TreeNode *pRoot = NULL;
for (int i = 0; i < strlen(str); i++)
{
CreateTree(pRoot, str[i]);
}
for (int i = 0; i < n; i++)
{
scanf("%s", str);
TreeNode *pRoot1 = NULL;
for (int j = 0; j < strlen(str); j++)
{
CreateTree(pRoot1, str[j]);
}
if (IsEqual(pRoot, pRoot1))
{
printf("YES\n");
}
else
{
printf("NO\n");
}
DeleteTree(pRoot1);
}
DeleteTree(pRoot);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: