求树的高度(递归)c
int high(Node a){
if(!a)
return 0;
else{
return high(a->left)>high(a->right)?high(a->left)+1:high(a->right)+1;//可以用最后的往上面跑比较容易理解
}
}
完整代码
#include
#include
typedef struct Tree{
int val;
struct Tree *left,*right;
}Tree,*Node;
void Creat(Node *a,int e){
if((*a)==NULL){
(*a)=(Node)malloc(sizeof(Tree));
(*a)->left=NULL;
(*a)->right=NULL;
(*a)->val=e;
return ;
}
if((*a)->val>e){
Creat(&((*a)->left),e);
}
else{
Creat(&((*a)->right),e);
}
}
void mid(Node a){//中序遍历
if(!a){
return;
}
else{//printf---先序遍历
mid(a->left);
printf("%d ",a->val);
mid(a->right);
//printf后序
}
}
int high(Node a){
if(!a)
return 0;
else{
return high(a->left)>high(a->right)?high(a->left)+1:high(a->right)+1;
}
}
int main(){
Node T=NULL;
int n;
scanf("%d",&n);
for(int i=0;i