• 树的孩子兄弟节点


    #include <iostream>
    using namespace std;
    
    typedef struct CSNode
    {
        char        data;
        struct CSNode * firstchild , * nextsibling ;
    }* CSTree;
    
    
    //====================================================
    #define MAXSIZE 10
    CSTree    q[MAXSIZE];
    int count=0;
        
    //初始化
    void init_cstree(CSTree &tree)
    {
        
        tree->firstchild = NULL;
        tree->nextsibling = NULL;
    }
    
    //创建树
    void creat_cstree(CSTree &T)
    {
    
        FILE *fin=fopen("树的孩子兄弟表示法.txt","r");  
        char fa=' ',ch=' ';
        for( fscanf(fin,"%c%c",&fa,&ch); ch!='#'; fscanf(fin,"%c%c",&fa,&ch) ) 
        {      
            CSTree p=(CSTree)malloc(sizeof(CSTree)); 
            init_cstree(p);
            p->data=ch;
            q[++count]=p;
    
            if('#' == fa)
                T=p;
            else
            {
                CSTree s = (CSTree)malloc(sizeof(CSTree));
                int i;
                for(i=1;i<=MAXSIZE;i++)
                {
                    if(q[i]->data == fa)    
                    {
                        s=q[i];
                        break;
                    }
                }
                 if(! (s->firstchild) )        //如果该双亲结点还没有接孩子节点
                    s->firstchild=p;
                else        //如果该双亲结点已经接了孩子节点
                {
                    CSTree temp=s->firstchild;
                    while(NULL != temp->nextsibling)
                    {
                        temp=temp->nextsibling;
                    }
                    temp->nextsibling=p;
                }
            }
        } 
        fclose(fin);
    }
    //前序遍历
    void print_cstree(CSTree &tree)
    {
            cout<<tree->data<<"  ";
            if(tree->firstchild!=NULL)
                print_cstree(tree->firstchild);
            if(tree->nextsibling!=NULL)
                print_cstree(tree->nextsibling);
    }
    //输出树中所有从根到叶子结点的路径的算法
    //void allpath_tree()
    int main()
    {
        CSTree    cstree;
        cstree=(CSTree)malloc(sizeof(CSTree));
        init_cstree(cstree);
        creat_cstree(cstree);
        //输出树
        print_cstree(cstree);
        cout<<endl;
        return 0;
    }
    

      


  • 相关阅读:
    BestCoder Round #86 1001
    Codeforces Round #365 (Div. 2) B
    Codeforces Round #365 (Div. 2) A
    Codeforces Round #129 (Div. 2) C
    Codeforces Round #129 (Div. 2) B
    Android.mk 文件语法详解
    RDS和ROS使用小结
    电力企业计量生产需求系统解决方案
    android 修改framework下资源文件后如何编译
    USB port 如何识别不同的Charger类型
  • 原文地址:https://www.cnblogs.com/zhanglanyun/p/2198248.html
Copyright © 2020-2023  润新知