• Source
    1. #include<stdio.h>
    2. #include<stdlib.h>
    3. typedef struct d
    4. {
    5. int root;
    6. struct d *left;
    7. struct d *right;
    8. }TREE;
    9.  
    10. TREE *parent=NULL, *location=NULL;
    11. TREE *create(TREE *t, int num)
    12. {
    13. if(t==NULL){
    14. t = (TREE *) malloc(sizeof(TREE) );
    15. t->root=num;
    16. t->left=t->right=NULL;
    17. }
    18.  
    19. else if(num<t->root)
    20. t->left=create(t->left,num);
    21. else if(num>t->root)
    22. t->right=create(t->right, num);
    23. return t;
    24. }
    25.  
    26. void print(int height, TREE *t)
    27. {
    28. int i=0;
    29. if(NULL!=t){
    30. print(height+1, t->right);
    31. printf("\n ");
    32.  
    33. for(i=0;i<height;i++)
    34. printf(" ");
    35.  
    36. printf(" %d ",t->root);
    37. print(height+1, t->left);
    38.  
    39. }
    40.  
    41. }
    42.  
    43. void search(int item,TREE *ptr)
    44. {
    45. while( item!=ptr->root)
    46. {
    47. parent=ptr;
    48. if(item<ptr->root)
    49. ptr=ptr->left;
    50.  
    51. else
    52. ptr=ptr->right;
    53.  
    54. location=ptr; // ptr is changed
    55.  
    56. }
    57. }
    58.  
    59. int sma(TREE *t)
    60. {
    61.  
    62. if(t->root==NULL)
    63. return 0;
    64. while(t->left!=NULL){
    65. t=t->left;
    66. }
    67. //printf("do\n");
    68. return t->root;
    69. }
    70.  
    71. int main()
    72. {
    73. TREE *tree=NULL, *x, *y;
    74. int n;
    75. while(1){
    76.  
    77. printf("\ngive value :");
    78. scanf("%d",&n);
    79. if(n==999)
    80. break;
    81. tree=create(tree, n);
    82. }
    83.  
    84. print(1, tree); // ****************** printing the tree
    85. printf("\nGive value to find location & parent:");
    86. scanf("%d",&n);
    87. search(n,tree); // ***************** Parent
    88.  
    89. if(location==NULL)
    90. printf("It have no Parent\n");
    91. else
    92. printf("\nThe parent of node is %d given value %d\n",parent->root, location->root);
    93.  
    94.  
    95. // *************************************************** the part of successor
    96.  
    97. x=location;
    98.  
    99. y=parent;
    100.  
    101. if(x==NULL)
    102. x=tree; // if the given number is root
    103.  
    104.  
    105. if(x->right!=NULL){
    106. int minimum=sma(x->right);
    107. printf("The successor is %d of %d\n",minimum, x->root);
    108. }
    109. else{
    110. while(y!=NULL && y->right!=NULL && (x->root== y->right->root) )
    111. {
    112. x=y;
    113. search(y->root, tree);
    114. y=parent;
    115. }
    116. printf("The successor is %d\n",y->root);
    117. }
    118.  
    119. free(tree);
    120. getchar();
    121. return 0;
    122. }