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