19年冬季第四题 PAT甲级 1167 Cartesian Tree (30分)超级详解不AC都难

痛定思痛。 2023-07-02 07:23 138阅读 0赞

题目:

7-4 Cartesian Tree (30分)

A Cartesian tree is a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8, 15, 3, 4, 1, 5, 12, 10, 18, 6 }, the min-heap Cartesian tree is shown by the figure.

CTree.jpg

Your job is to output the level-order traversal sequence of the min-heap Cartesian tree.
Input Specification:

Each input file contains one test case. Each case starts from giving a positive integer N (≤30), and then N distinct numbers in the next line, separated by a space. All the numbers are in the range of int.
Output Specification:

For each test case, print in a line the level-order traversal sequence of the min-heap Cartesian tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.

  1. Sample Input:
  2. 10
  3. 8 15 3 4 1 5 12 10 18 6
  4. Sample Output:
  5. 1 3 5 8 4 6 15 10 12 18

题目大意:

给定一个二叉最小堆(Cartesian Tree)的中序序列,输出层序遍历序列。

这道题的题眼:

1.给出的是个min-heap
最小堆,即所有父节点不大于子节点的二叉树。如果找到了目前区间的最小值,那就是个父节点。
2.给出的顺序是inorder
中序,也就是LNR。是不是想到了递归和分而治之的老方法了?
3.输出的顺序是level-order
层序。如果不建树,就是开个大数组,按照下标放;如果建树,就得用BFS遍历树了。

这道题的陷阱:

没有说是哪种二叉树,如果是最极端的那种,就是每行只有一个节点,画个草图就是:
在这里插入图片描述
4是3的左孩子,3是2的左孩子,2是1的左孩子。
题目说最多30个节点,如果不建树那得需要2的30次方那么大的数组了,那会遇到编译不通过。所以这道题还得建树。

我自己写的测试用例:

改变节点的数量和二叉树的内部结构。不过这道题本身是没啥坑的。

  1. //输入1
  2. 8
  3. 60 58 38 52 8 82 25 70
  4. //输出1
  5. 8 38 25 58 52 82 70 60
  6. //输入2
  7. 13
  8. 8 4 2 9 5 10 1 11 6 12 3 7 13
  9. //输出2
  10. 1 2 3 4 5 6 7 8 9 10 11 12 13

附上满分答案:

  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4. int n,k;
  5. vector<int> v;
  6. struct tree{
  7. int data;
  8. tree *l,*r;
  9. }*T;
  10. tree* check(int low,int high){
  11. if(low<0||low>high)return NULL;
  12. tree *t=new tree;
  13. int minn=low;
  14. for(int j=low;j<=high;j++){
  15. if(v[minn]>v[j])minn=j;
  16. }
  17. t->data=v[minn];
  18. t->l=check(low,minn-1);
  19. t->r=check(minn+1,high);
  20. return t;
  21. }
  22. int main(){
  23. scanf("%d",&n);
  24. for(int i=0;i<n;i++){
  25. scanf("%d",&k);
  26. v.push_back(k);
  27. }
  28. T=check(0,n-1);
  29. int flag=0;
  30. queue<tree*> q;
  31. q.push(T);
  32. while(!q.empty()){
  33. tree *t=q.front();
  34. if(flag==1)cout<<" ";
  35. else flag=1;
  36. cout<<t->data;
  37. if(t->l)q.push(t->l);
  38. if(t->r)q.push(t->r);
  39. q.pop();
  40. }
  41. return 0;
  42. }

发表评论

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

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

相关阅读