1. 程式人生 > 實用技巧 >樹——儲存結構

樹——儲存結構

樹——儲存結構


雙親表示法(順序儲存)

雙親表示法:每個節點中儲存指向雙親的“指標”

#define MAX_TREE_SIZE 100	//樹中最多的結點數
typedef struct{	//樹的結點定義
    ElemType data;	//資料元素
    int parent;	//雙親位置域
}PTNode;
typedef struct{	//樹型別定義
    PTNode nodes[MAX_TREE_SIZE];	//雙親表示,由各個結點組成的陣列
    int n;	//結點數
}PTree;

孩子表示法(順序+鏈式儲存)

順序儲存各個結點,每個節點中儲存孩子連結串列頭指標

struct CTNode{
    int child;//孩子結點在陣列中的位置
    struct CTNode *next;//下一個孩子
};
typedef struct {
    ElemType data;
    struct CTNode *firstChild;//第一個孩子
}CTBox;
typedef struct{
    CTBox nodes[MAX_TREE_SIZE];
    int n,r;//結點數和根的位置
}CTree;

孩子兄弟表示法(鏈式儲存)

//樹的儲存——孩子兄弟表示法
typedef struct CSNode{
    ElemType data;//資料域
    struct CSNode *firstchild,*nextsibling;//第一個孩子和右兄弟指標
}CSNode,*CSTree;

優點:利用我們熟悉的二叉樹操作來處理樹

森林二叉樹相互轉換