How to determine whether a binary tree is complete?

前端 未结 16 1372
渐次进展
渐次进展 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:51

    //Helper function
    
    int depth (struct tree * n)
    {
       int ld,rd;
    
       if (n == NULL) return 0;
    
       ld=depth(n->left);
       ld=depth(n->right);
    
       if (ld>rd)
          return (1+ld);
       else
          return (1+rd);
    
    }
    
    
    //Core function
    
    int isComplete (struct tree * n)
    {
       int ld,rd;
    
       if (n == NULL) return TRUE;
    
       ld=depth(n->left);
       rd=depth(n->right);
    
       return(ld==rd && isComplete(n->left) && isComplete(n->right));
    
    }
    

提交回复
热议问题