[树] 树的存储结构

表示方法

  • 双亲表示法:数组;元素结点添加指示Parent的指示器
  • 孩子表示法:数组+单链表;元素节点有Child结点(child|next),child是数据域,用来存储某个结点在表头数组中的下标,next是指针域,用来存储指向某节点的下一个孩子结点的指针;和表头结点(data|firstchild),data是数据域,存储结点数据信息,firstchild是头指针域,存储该结点的孩子链表的头指针
  • 孩子兄弟表示法

双亲表示法

双亲表示法
采用的一组连续的存储空间来存储每个节点。 根节点没有双亲,所以其在数组中存储的值为-1。 其余的节点,只需要存储其父节点对应的数组下标即可。

// 双亲表示法
#define MAX_SIZE 100
typedef int ElemType;

typedef struct PTNode{
    ElemType data;
    int parent;
}PTNode;

typedef struct PTree
{
    PTNode nodes[MAX_SIZE];
    int n;
}PTree;

孩子表示法

将每个节点的孩子节点都用单链表连接起来形成一个线性结构,n个节点具有n个孩子链表。

孩子表示法

孩子表示法

// 孩子表示法
typedef int ElemType;
#define MAX_SIZE 100
typedef struct CNode
{
    int child;
    struct CNode *next;
}CNode;

typedef struct PNode
{
    ElemType data;
    struct CNode *child;
}PNode;

typedef struct CTree
{
    PNode nodes[MAX_SIZE];
    int n;
}CTree;

孩子兄弟表示法

以二叉链表作为树的存储结构,又称二叉树表示法。

二叉链表结点
转换前
转换后

typedef int ElemType;
typedef struct Node
{
    ElemType data;
    struct Node *FirstChild;
    struct Node *NextBrother;
    
}Node,TREE;

reference

图解 数据结构:树的存储结构

posted @ 2022-06-24 19:17  deadright  阅读(59)  评论(0)    收藏  举报