The order of a Tree

系统管理员 2022-05-12 05:42 238阅读 0赞

Problem Description
As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely:

  1. insert a key k to a empty tree, then the tree become a tree with
    only one node;
  2. insert a key k to a nonempty tree, if k is less than the root ,insert
    it to the left sub-tree;else insert k to the right sub-tree.
    We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.

Input
There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n.

Output
One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic.

Sample Input
4

1 3 4 2

Sample Output
1 3 2 4
分析

  1. 二叉排序树 保证左结点比上一结点小 右结点比上一结点大

代码总览:

  1. #include <cstdio>
  2. #include <iostream>
  3. #include <cstring>
  4. using namespace std;
  5. typedef struct BiTreeNode
  6. {
  7. int data;
  8. struct BiTreeNode *lchild,*rchild;
  9. }*BiTree;
  10. void add(BiTree &T,int val)
  11. {
  12. if(T==NULL)
  13. {
  14. T=new BiTreeNode();
  15. T->data=val;
  16. T->lchild=T->rchild=NULL;
  17. }
  18. else if(T->data>val)
  19. add(T->lchild,val);
  20. else
  21. add(T->rchild,val);
  22. }
  23. void PreOrder(BiTree T,int flag)
  24. {
  25. if(T==NULL)
  26. return;
  27. else{
  28. if(!flag)
  29. printf(" ");
  30. //cout<<T->data;
  31. printf("%d",T->data);
  32. PreOrder(T->lchild,0);
  33. PreOrder(T->rchild,0);
  34. }
  35. }
  36. int main()
  37. {
  38. int n,v;
  39. BiTree T;
  40. while(scanf("%d",&n)!=EOF)
  41. {
  42. T=NULL;
  43. for(int i=0;i<n;i++)
  44. {
  45. scanf("%d",&v);
  46. add(T,v);
  47. }
  48. PreOrder(T,1);
  49. // printf("\n");
  50. }
  51. }

发表评论

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

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

相关阅读