数据结构实验之查找一:二叉排序树

ゝ一纸荒年。 2022-07-14 08:19 288阅读 0赞

数据结构实验之查找一:二叉排序树

Time Limit: 400MS Memory Limit: 65536KB

Submit Statistic

Problem Description

对应给定的一个序列可以唯一确定一棵二叉排序树。然而,一棵给定的二叉排序树却可以由多种不同的序列得到。例如分别按照序列{3,1,4}和{3,4,1}插入初始为空的二叉排序树,都得到一样的结果。你的任务书对于输入的各种序列,判断它们是否能生成一样的二叉排序树。

Input

输入包含若干组测试数据。每组数据的第1行给出两个正整数N (n < = 10)和L,分别是输入序列的元素个数和需要比较的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列生成一颗二叉排序树。随后L行,每行给出N个元素,属于L个需要检查的序列。
简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。

Output

对每一组需要检查的序列,如果其生成的二叉排序树跟初始序列生成的二叉排序树一样,则输出”Yes”,否则输出”No”。

Example Input

  1. 4 2
  2. 3 1 4 2
  3. 3 4 1 2
  4. 3 2 4 1
  5. 2 1
  6. 2 1
  7. 1 2
  8. 0

Example Output

  1. Yes
  2. No
  3. No

Hint

此题需要注意的是:是判断是否为同一颗树而不是判断不同序列是否可以由一棵树遍历得到

  1. #include<cstdio>
  2. #include<cstring>
  3. #include<malloc.h>
  4. #include<cstdlib>
  5. using namespace std;
  6. int flag;//标记是否是同一棵二叉树
  7. struct node
  8. {
  9. int data;
  10. struct node *lc,*rc;
  11. };
  12. //创建二叉树
  13. struct node *creat(struct node *root,int e)
  14. {
  15. if(root==NULL)
  16. {
  17. root=new node;
  18. root->data=e;
  19. root->lc=root->rc=NULL;
  20. }
  21. else
  22. {
  23. if(root->data>e)
  24. {
  25. root->lc=creat(root->lc,e);
  26. }
  27. else
  28. {
  29. root->rc=creat(root->rc,e);
  30. }
  31. }
  32. return root;
  33. };
  34. //判断是否为同一颗二叉树
  35. int judge(struct node *root1,struct node *root2)
  36. {
  37. if(root1==NULL&&root2==NULL)
  38. {
  39. flag=1;
  40. }
  41. else if(root1!=NULL&&root2!=NULL)//不为空树,递归查找判断
  42. {
  43. if(root1->data==root2->data)
  44. {
  45. if(judge(root1->lc,root2->lc)==1&&judge(root2->rc,root2->rc)==1)
  46. {
  47. flag=1;
  48. }
  49. }
  50. }
  51. return flag;
  52. }
  53. int main()
  54. {
  55. int n,m;
  56. while(~scanf("%d",&n)&&n)
  57. {
  58. scanf("%d",&m);
  59. struct node *root;
  60. root=NULL;
  61. int tree[20];//初始序列数组
  62. int tree2[20];//待检查的序列数组
  63. for(int i=0;i<n;i++)
  64. {
  65. scanf("%d",&tree[i]);
  66. root=creat(root,tree[i]);
  67. }
  68. while(m--)
  69. {
  70. struct node *root2;
  71. root2=NULL;
  72. for(int i=0;i<n;i++)//待检查的序列每次都需要重建二叉树
  73. {
  74. scanf("%d",&tree2[i]);
  75. root2=creat(root2,tree2[i]);
  76. }
  77. flag=0;//标记变量初始化为0
  78. int t=judge(root,root2);
  79. if(t==1)
  80. {
  81. printf("Yes\n");
  82. }
  83. else
  84. {
  85. printf("No\n");
  86. }
  87. }
  88. }
  89. return 0;
  90. }

发表评论

表情:
评论列表 (有 0 条评论,288人围观)

还没有评论,来说两句吧...

相关阅读