孩子兄弟表示法构建一棵树 D S Q C # # U A # # # E # G L # # # #


#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#define ElemType char
using namespace std;
typedef struct CSNode{
    ElemType data;
    struct CSNode *firstchild,*nextsibling;
}CSNode,*CSTree;
void CreatCSTree(CSTree &T){
    ElemType ch;
    cin>>ch;
    getchar();
    if(ch=='#'){
        T=NULL;
    }
    else{
        T=(CSTree)malloc(sizeof(CSNode));
        T->data=ch;
        CreatCSTree(T->firstchild);
        CreatCSTree(T->nextsibling);
    }
}
void visit(CSTree &T){
    if(T){
        cout<<T->data<<" ";
        visit(T->firstchild);
        visit(T->nextsibling);
    }
}
int Leaves(CSTree T){
    if(T==NULL){
        return 0;
    }
    if(T->firstchild==NULL){
        return 1+Leaves(T->nextsibling);
    }
    else{
        return Leaves(T->firstchild)+Leaves(T->nextsibling);
    }
}//找寻树的叶子节点数
int TreeHeight(CSTree &T){
    int ch,nh;
    if(T==NULL){
        return 0;
    }
    ch=TreeHeight(T->firstchild);//获得第一个子树的高度
    nh=TreeHeight(T->nextsibling);//获得兄弟树的高度
    if(ch+1>nh){return ch+1;}//判断子树和兄弟树的高度
    else {return nh;}
}//返回树的高度
int main(){
    CSTree T;
    cout<<"输入树:";
    CreatCSTree(T);
    cout<<"遍历树:";
    visit(T);
    cout<<endl;
    cout<<"树的叶子节点数:"<<Leaves(T)<<endl;
    cout<<"树的高度:"<<TreeHeight(T)<<endl;
    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM