fork(2) download
  1. #include<iostream>
  2. #define infinity 999
  3. using namespace std;
  4. struct tnode
  5. {
  6. tnode* lchild;
  7. int data;
  8. tnode* rchild;
  9. int *aptr;
  10. int ind;
  11. tnode()
  12. {
  13. lchild=NULL;
  14. aptr=NULL;
  15. ind=0;
  16. rchild=NULL;
  17. }
  18. };
  19.  
  20. tnode* create(tnode* root,int *s1,int *s2,int *s3,int level,int &cnt)
  21. {
  22. if(level==0)
  23. {
  24. root=new tnode();
  25. if(cnt==1)
  26. {
  27. root->aptr=s1;
  28. cnt++;
  29. return root;
  30. }
  31. else if(cnt==2)
  32. {
  33. root->aptr=s2;
  34. cnt++;
  35. return root;
  36. }
  37. else if(cnt==3)
  38. {
  39. root->aptr=s3;
  40. cnt++;
  41. return root;
  42. }
  43. else
  44. return root;
  45. }
  46. root=new tnode();
  47. root->lchild=create(root->lchild,s1,s2,s3,level-1,cnt);
  48. root->rchild=create(root->rchild,s1,s2,s3,level-1,cnt);
  49. return root;
  50. }
  51. void fun(tnode* root,int level,int n)
  52. {
  53. if(level==0)
  54. {
  55. if((root->ind>=n)||(root->aptr==NULL))
  56. {
  57. root->data=infinity;
  58. return;
  59. }
  60. else
  61. {
  62. root->data=root->aptr[root->ind];
  63. return;
  64. }
  65. }
  66. fun(root->lchild,level-1,n);
  67. fun(root->rchild,level-1,n);
  68. root->data=min(root->lchild->data,root->rchild->data);
  69. }
  70. void display(tnode* root)
  71. {
  72. if(root)
  73. {
  74. display(root->lchild);
  75. cout<<root->data<<" ";
  76. display(root->rchild);
  77. }
  78. }
  79. void get_roottoleaf(tnode* root,int k,int level)
  80. {
  81. if(level==0)
  82. {
  83. if(root->data==k)
  84. {
  85. root->ind++;
  86. return;
  87. }
  88. else
  89. return;
  90. }
  91. get_roottoleaf(root->lchild,k,level-1);
  92. get_roottoleaf(root->rchild,k,level-1);
  93. }
  94. int main()
  95. {
  96. tnode* root=NULL;
  97. int s1[]={2,5,8,12};
  98. int s2[]={1,3,4,6};
  99. int s3[]={7,9,10,11};
  100. int level=2,cnt=1;
  101. int n=sizeof(s1)/sizeof(s1[0]);
  102. root=create(root,s1,s2,s3,level,cnt);
  103. for(int i=0;i<=6;i++)
  104. {
  105. fun(root,level,n);
  106. get_roottoleaf(root,root->data,level);
  107. }
  108. cout<<root->data<<" is the median of the sorted array.\n";
  109. return 0;
  110. }
  111.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
7 is the median of the sorted array.