假设二叉树采用二叉链存储结构,设计一个算法求二叉树中结点值的层次

#include<bits/stdc++.h>

typedef struct node

{

 char data;

 struct node *lchild,*rchild;

}BTNode;

void Greate(BTNode *&T)

{

 char ch;

 scanf("%c",&ch);

 if(ch=='#') T=NULL;

扫描二维码关注公众号,回复: 15160269 查看本文章

 else 

 {

  T=(BTNode*)malloc(sizeof(BTNode));

  T->data=ch;

  Greate(T->lchild);

  Greate(T->rchild);

 }

}

void Disp(BTNode *T)

{

 if(T!=NULL)

 {

  printf("%c",T->data);

  if(T->lchild!=NULL || T->rchild!=NULL)

  {

   Disp(T->lchild);

   if(T->rchild!=NULL) Disp(T->rchild);

  }

 }

}

int Level(BTNode *T,char x,int h)

{

 int l;

 if(T==NULL) return (0);

 else if(T->data==x) return (h);

 else

 {

  l=Level(T->lchild,x,h+1);

  if(l!=0) return (1);

  else return (Level(T->rchild,x,h+1));

 }

}

int main()

{

 BTNode *T;

 Greate(T);

 Disp(T);

 int h;

 char ch='A';

 h=Level(T,ch,1);

 if(h==0) printf("不存在此节点");

 else printf("%c节点的层次为%d",ch,h);

 return 0;

}

猜你喜欢

转载自blog.csdn.net/2302_77099705/article/details/130909609