数据结构趣题——判断完全二叉树

   1: #include "stdio.h"
   2:  
   3: typedef struct BiTNode {
   4:     char data;   /*结点的数据域*/
   5:     struct BiTNode *lchild , *rchild;  /*指向左孩子和右孩子*/
   6: } BiTNode , *BiTree;
   7:  
   8: /*创建一棵二叉树*/
   9: void CreatBiTree(BiTree *T , int *level1 , int level2) {
  10:     char c;
  11:  
  12:     scanf("%c", &c);
  13:  
  14:     if(c == ' ') *T = NULL;
  15:     else {
  16:         *T = (BiTNode * )malloc(sizeof(BiTNode));           /*创建根结点*/
  17:         (*T)->data = c;                                    /*向根结点中输入数据*/
  18:  
  19:  
  20:         if(*level1 < level2) {
  21:             *level1 = level2;
  22:         }
  23:  
  24:  
  25:         CreatBiTree(&((*T)->lchild), &(*level1), level2 + 1); /*递归地创建左子树*/
  26:         CreatBiTree(&((*T)->rchild), &(*level1), level2 + 1); /*递归地创建右子树*/
  27:     }
  28: }
  29:  
  30:  
  31: int JusticCompleteBiTree(BiTree T, int level , int n, int flag) {
  32:     if(!T) {
  33:         return 1;
  34:     }
  35:  
  36:     if(level == n)
  37:     {
  38:  
  39:         if(T->lchild == NULL && T->rchild != NULL) return 0;
  40:  
  41:         if(flag == 0) { /*同层的前面的结点无空指针*/
  42:             if(T->rchild == NULL) flag = 1; /*出现空指针*/
  43:         }
  44:         else if(flag == 1) { /*同层的前面的结点有空指针*/
  45:             if(T->lchild != NULL || T->rchild != NULL)  return 0;
  46:         }
  47:     }
  48:  
  49:     if(level != n && level != n + 1)
  50:     {
  51:         if(T->lchild == NULL || T->rchild == NULL) return 0;
  52:     }
  53:  
  54:     if(!JusticCompleteBiTree(T->lchild, level + 1, n, flag)) return 0;
  55:  
  56:     if(!JusticCompleteBiTree(T->rchild, level + 1, n, flag)) return 0;
  57:  
  58:     return 1;
  59: }
  60:  
  61: int  main()
  62: {
  63:     BiTree T;
  64:     int level1 = 0;
  65:     printf("Please type some character to creat a binary tree\n");
  66:     CreatBiTree(&T, &level1, 0);
  67:  
  68:     if(JusticCompleteBiTree(T, 0, level1 - 1, 0))  printf("It is a complete binary tree\n");
  69:     else  printf("It is NOT a complete binary tree\n");
  70:  
  71:     return 0;
  72: }
    原文作者:红脸书生
    原文地址: https://www.cnblogs.com/steven_oyj/archive/2010/05/29/1746952.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞