How to determine whether a binary tree is complete?

前端 未结 16 1690
渐次进展
渐次进展 2021-01-02 19:15

A complete binary tree is defined as a binary tree in which every level, except possibly the deepest, is completely filled. At deepest level, all nodes must be as far left a

16条回答
  •  太阳男子
    2021-01-02 19:45

    int height (node* tree, int *max, int *min) {
    
      int lh = 0 , rh = 0 ;
      if ( tree == NULL )
        return 0;
      lh = height (tree->left,max,min) ;
      rh = height (tree->right,max,min) ;
      *max = ((lh>rh) ? lh : rh) + 1 ;
      *min = ((lh>rh) ? rh : lh) + 1 ;
      return *max ;
    }
    
    void isCompleteUtil (node* tree, int height, int* finish, int *complete) {
      int lh, rh ;
      if ( tree == NULL )
        return ;
      if ( height == 2 ) {
        if ( *finish ) {
          if ( !*complete )
            return;
          if ( tree->left || tree->right )
            *complete = 0 ;
          return ;
        }
        if ( tree->left == NULL && tree->right != NULL ) {
          *complete = 0 ;
          *finish = 1 ;
        }
        else if ( tree->left == NULL && tree->right == NULL )
          *finish = 1 ;
        return ;
      }
      isCompleteUtil ( tree->left, height-1, finish, complete ) ;
      isCompleteUtil ( tree->right, height-1, finish, complete ) ;
    }
    
    int isComplete (node* tree) {
      int max, min, finish=0, complete = 1 ;
      height (tree, &max, &min) ;
      if ( (max-min) >= 2 )
        return 0 ;
      isCompleteUtil (tree, max, &finish, &complete) ;
      return complete ;
    }
    

提交回复
热议问题