关于树

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_40862011/article/details/84977985

判定二叉排序树

typedef struct {
  KeyType key;  
  ... ...   // 其他数据域
} TElemType;
typedef struct BiTNode {
  TElemType data;
  struct BSTNode  *lchild, *rchild;
}BSTNode, *BSTree;
Status IsBSTree(BSTree T){
      BSTree p, q;
       if(T) {
       p = T->lchild;
       q = T->rchild;
        if(p && T->data.key <= p->data.key) return FALSE;
        if(q && T->data.key >= q->data.key) return FALSE;
          if(IsBSTreee(p))
            return IsBSTree(q);
             return FALSE; 
       }
     return TRUE;
}

双亲表示法

typedef struct {
   TElemType data;  // 元素值
   int     parent;  // 双亲位置,根结点的parent值为-1
} PTNode;           // 结点类型
typedef struct {
   PTNode  * noeds; // 结点存储空间
   int  r, nodeNnm; // 根的位置和结点数
} PTree;            // 树的双亲存储结构类型

求深度

int PTreeDepth(PTree T){
     int i, j, a, b;
     for(i = 0; i < T.n; i++){
          b = 0;
      for(j = i; j > 0; j = T.nodes[j].parent)
          b ++;
          if(b > a)  a = b;
      }
        return a + 1;  
}

双亲孩子表示法

typedef struct ChildNode {      // 孩子结点
   int childIndex;
   struct ChildNode *nextChild;
} ChildNode;                    // 孩子结点类型
typedef struct  {
   TElemType data;
   int     parent;               // 双亲位置
   struct ChildNode *firstChild; // 孩子链表头指针
} PCTreeNode;                    // 结点类型
typedef struct {
   PCTreeNode *nodes;       // 结点存储空间
   int    nodeNum, r;       // 结点数和根的位置
} PCTree;

求深度

int PCTreeDepth(PCTree T){
     int depth, max, index;
     ChildNode *a, *b;
     if( !T.nodes[T.r].firstChild) return 1;
     for(b = T.nodes[T.r].firstChild; b ;b = b->nextChild){
        depth = 1;
        index = b->childIndex;
        a = b;
        while(a){
         a = T.nodes[index].firstChild;
         index = a->childIndex;
         depth ++;
       }
      if(max < depth)  max = depth;
     }
  return max;
}

孩子兄弟表示法

typedef struct CSTNode {
  TElemType  data;                           // 数据域
  struct CSTNode  *firstChild, *nextSibling; // 最左孩子指针、右兄弟指针
} CSTNode, *CSTree;                          // 孩子兄弟链表

求深度

int TreeDepth(CSTree T){
    int left, right, depth;
    if(T == NULL) {
       depth = 0;
    } else {
       left = TreeDepth(T->firstChild);
      right = TreeDepth(T->nextSibling);
      depth = left + 1 > right ? left + 1 : right ;
    }
      return depth;
}

猜你喜欢

转载自blog.csdn.net/weixin_40862011/article/details/84977985