#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; }