孩子兄弟表示法構建一棵樹 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