1. 程式人生 > >資料結構——樹的孩子表示法

資料結構——樹的孩子表示法

#include <iostream>
using namespace std;

#define MAX_TREE_SIZE 100
typedef struct Cnode        //孩子節點
{
    char        child;
    struct    Cnode * next;
}* CNode;
typedef struct     
{
    char        data;
    int            parent;        //雙親位置域
    CNode    firstchild;    //孩子連結串列頭指標
}PTNode;
typedef struct        //樹結構
{
    PTNode node[MAX_TREE_SIZE];
    int count;        //節點個數
}CTree;

//初始化樹
void init_ptree(CTree &tree)
{
    tree.count=-1;
    int i;
    for(i=0;i<MAX_TREE_SIZE;i++)
        tree.node[i].firstchild=NULL;
}
//新增節點
void add_ptnode(CTree &tree, PTNode ptnode)
{
    tree.count++;
    tree.node[tree.count].data = ptnode.data;
    tree.node[tree.count].parent = ptnode.parent;
    
    CNode temp=(CNode)malloc(sizeof(CNode));
    temp->child=ptnode.data;
    temp->next=NULL;

    if(ptnode.parent>=0)
    {
        if(NULL == tree.node[ptnode.parent].firstchild)        //尚未接孩子
        {
            tree.node[ptnode.parent].firstchild = temp;
        }
        else
        {
            CNode pre=tree.node[ptnode.parent].firstchild;    
            while(NULL != pre->next)    
                pre=pre->next;
            pre->next=temp;
        }
    }
}

//輸出樹
void print_ctree(CTree &tree)
{
    int i;
    for(i=0;i<=tree.count;i++)
    {
        cout<<"    "<<i<<"        "<<tree.node[i].data<<"        "<<tree.node[i].parent<<"      ";
        CNode temp=tree.node[i].firstchild;
        while(temp!=NULL)
        {
            cout<<temp->child<<"   ";
            temp=temp->next;
        }
        cout<<endl;
    }
}

int main()
{
    FILE *fin=fopen("樹的表示法.txt","r");

    CTree ctree;
    init_ptree(ctree);
    PTNode ptnode;

    while(fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent)!=EOF)
    {
        add_ptnode(ctree,ptnode);
        fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent);
    }
    //輸出樹
    cout<<"陣列下標  節點值  雙親位置   子節點"<<endl;
    print_ctree(ctree);

    fclose(fin);
    return 0;
}