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


       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: }
  • 相关阅读:
    Timer 实现2秒4秒连环炸
    Java中的注解
    PHP连接打印机
    php同步mysql两个数据库中表的数据
    thinkphp 两表、三表联合查询
    ereg/eregi报错处理办法
    ThinkPHP3.2判断手机端访问并设置默认访问模块的方法
    使用PHP获取时间今天 明天 昨天 时间戳的详解
    jquery获取radio和select选中值
    php开启mysqli扩展之后如何连接数据库
  • 原文地址:https://www.cnblogs.com/steven_oyj/p/1746952.html
Copyright © 2020-2023  润新知