二叉树结点的层次
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node{ //二叉树的链式存储结点
char data;
int depth;
struct Node *Lchild;
struct Node *Rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree *root){ //形参采用二级指针,实参为结点孩子域地址
char ch;
ch=getchar();
if(ch=='#') *root=NULL;
else{
*root=(BiTree)malloc(sizeof(BiTree));
(*root)->data=ch;
CreateBiTree(&((*root)->Lchild));
CreateBiTree(&((*root)->Rchild));
}
}
void Visit(char data,int a){
printf("(%c,%d)",data,a);
}
int PostTreeDepth(BiTree T){
int hl,hr,h;
if(T==NULL) return 0;
else{
hl=PostTreeDepth(T->Lchild);
hr=PostTreeDepth(T->Rchild);
h=(hl>hr?hl:hr)+1;
T->depth=h;
return h;
}
}
void PreOrder(BiTree T,int h){ //先序递归遍历
if(T){
Visit(T->data,T->depth);
PreOrder(T->Lchild,h);
PreOrder(T->Rchild,h);
}
}
int main(){
BiTree T;
CreateBiTree(&T);
int h=PostTreeDepth(T);
PreOrder(T,h);
return 0;
}