【查找与定位算法】
问题描述:定位二叉树 bt 中结点值为 x 的结点及其所在的层次。
题目挺简单的,但是还是想了很久,说到底还是菜啊
代码如下:
#include<bits/stdc++.h>
#define telemtype char
using namespace std;
typedef struct node{
telemtype data;
struct node *lchild,*rchild;
} *Bitree;
void creatree(Bitree &tt)
{
char c;
cin>>c;
if(c=='#') tt=NULL;
else
{
tt=(node *)malloc(sizeof(node));
tt->data=c;
creatree(tt->lchild);
creatree(tt->rchild);
}
}
int check(char c,Bitree &t,int &num,int l)
{
if(t)
{
l++;
if(t->data==c)
{
num=l;
}
check(c,t->lchild,num,l);
check(c,t->rchild,num,l);
}
}
int main()
{
Bitree t;
creatree(t);
while(1)
{
cout<<"请输入需要查询的节点:"<<endl;
char c;
cin>>c;
int num;
check(c,t,num,0);
cout<<"结点所在层次为:"<<num<<endl;
}
}
努力加油a啊,(o)/~