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

梦里梦外; 2022-07-14 14:45 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
  4. #include <stdio.h>
  5. #include <iostream>
  6. #include <string.h>
  7. #include <stdlib.h>
  8. using namespace std;
  9. int n,m,i,j,T;
  10. struct tree
  11. {
  12. int data;
  13. struct tree *rchild,*lchild;
  14. };
  15. tree *creat(tree *root,int x)
  16. {
  17. if(root==NULL)
  18. {
  19. root = new tree;
  20. root->rchild = root->lchild = NULL;
  21. root->data = x;
  22. }
  23. else
  24. {
  25. if(root->data<x)
  26. {
  27. root->lchild = creat(root->lchild,x);
  28. }
  29. else
  30. {
  31. root->rchild = creat(root->rchild,x);
  32. }
  33. }
  34. return root;
  35. }
  36. bool cmptree(tree *r1,tree *r2)
  37. {
  38. if(r1==NULL &&r2==NULL)
  39. {
  40. return true;
  41. }
  42. else if(r1==NULL || r2==NULL)
  43. {
  44. return false;
  45. }
  46. if(r1->data!=r2->data)
  47. {
  48. return false;
  49. }
  50. if(cmptree(r1->lchild,r2->lchild)&&cmptree(r1->rchild,r2->rchild))
  51. {
  52. return true;
  53. }
  54. return false;
  55. }
  56. int main()
  57. {
  58. while(scanf("%d",&n),n!=0)
  59. {
  60. cin>>m;
  61. int str[1234];
  62. tree *p=NULL;
  63. for(i=0;i<n;i++)
  64. {
  65. cin>>str[i];
  66. p = creat(p,str[i]);
  67. }
  68. while(m--)
  69. {
  70. tree *p1=NULL;
  71. for(i=0;i<n;i++)
  72. {
  73. cin>>str[i];
  74. p1 = creat(p1,str[i]);
  75. }
  76. if(cmptree(p1,p))
  77. {
  78. cout<<"Yes"<<endl;
  79. }
  80. else
  81. {
  82. cout<<"No"<<endl;
  83. }
  84. }
  85. }
  86. return 0;
  87. }

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

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

发表评论

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

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

相关阅读