hamaXD

lab9 แบบผริ้น

Nov 21st, 2017
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct treenode {
  5.     struct treenode *left;
  6.     struct treenode *right;
  7.     int data;
  8. };
  9. typedef struct treenode TREENODE;
  10. typedef TREENODE *TREE;
  11.  
  12. void insert_node(TREE *tp, int value);
  13. void preorder_print(TREE t);
  14. int is_empty_tree ( TREE t );
  15. int root_value(TREE t);
  16. int is_perfect_tree(TREE t);
  17.  
  18. int main(){
  19.     TREE t = NULL;
  20.     int i = 0, tmp;
  21.     do{
  22.         printf("N%02d: ", i + 1);
  23.         scanf(" %d", &tmp);
  24.         if(tmp==0){
  25.             break;
  26.         }
  27.         insert_node(&t,tmp);
  28.         i++;
  29.     }while(tmp > 0);
  30.     preorder_print(t);
  31.     printf(" = %s\n", is_perfect_tree(t) ? "Yes" : "No");
  32.     return 0;
  33. }
  34. void insert_node(TREE *tp, int value) {
  35.     if (*tp == NULL) {
  36.     //  printf("tp == null\n");
  37.         *tp = malloc(sizeof(TREENODE));
  38.         (*tp)->data = value;  
  39.         (*tp)->left = NULL;
  40.         (*tp)->right = NULL;
  41.     }else if (value < (*tp)->data ){
  42.     //  printf("tp <<<\n");
  43.         insert_node(&((*tp)->left), value);
  44.     }else if (value > (*tp)->data ){
  45.     //  printf("tp >>>\n");
  46.         insert_node(&((*tp)->right), value);
  47.     }else{
  48.         printf("duplicate node\n");
  49.     }
  50. }
  51.  
  52. int is_empty_tree ( TREE t ){
  53.     if (t == NULL) {
  54.     //  printf("in empty null\n");
  55.         return 1;
  56.     }else{
  57.     //  printf("NO in empty null\n");
  58.         return 0;
  59.     }
  60. }
  61. int root_value(TREE t){
  62.     if (!is_empty_tree){
  63.         fprintf(stderr, "Tree is empty \n");
  64.         return -1;
  65.     }else{
  66.         return t->data;
  67.     }
  68. }
  69.  
  70. TREE ls_tree(TREE t){
  71. //  printf("left\n");
  72.     return t->left;
  73. }
  74. TREE rs_tree(TREE t){
  75. //  printf("right\n");
  76.     return t->right;
  77. }
  78.  
  79.  
  80. void preorder_print(TREE t){
  81.     if (!is_empty_tree(t)) {
  82.        
  83.         printf("%d\n", root_value(t));
  84.         preorder_print(ls_tree(t));  
  85.        
  86.         preorder_print(rs_tree(t));
  87.     }
  88. }
  89.  
  90.  
  91. int is_perfect_tree(TREE t){
  92.     if(t == NULL){
  93.         return 1;
  94.     }else if(t->left==NULL&&t->right==NULL){
  95.         return 1;
  96.     }else if(t->left==NULL||t->right==NULL){
  97.         return 0;
  98.     }else{
  99.         return is_perfect_tree(t->left)&&is_perfect_tree(t->right);
  100.     }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment