第十周日志

数据结构第七章关于二叉树寻找元素代码实现

include

include<stdio.h>

include<stdlib.h>

using namespace std;
static int count=1,b;

//树的定义(结点定义)
typedef char DataType;
typedef struct Node {
DataType data;
struct Node *lchild;
struct Node rchild;
} BiNode,
BiTree;

//创建树的二叉链表(递归)
void CreateBiTree(BiTree *bt)
{
char ch;
ch = getchar();
if(ch=='.') bt=NULL;
else
{
bt= (BiNode )malloc(sizeof(BiNode));
(
bt)->data=ch;
CreateBiTree(&((
bt)->lchild)); //生成左子树
CreateBiTree(&((
bt)->rchild)); //生成右子树
}
}

//输出二叉树的元素(先序)
void Print(BiTree bt)
{
if(bt==NULL)
return;
else
{
printf("%c ", bt->data);
Print(bt->lchild);
Print(bt->rchild);
}

}

//查找元素
void find(BiTree bt,int count,char a)
{

if(bt==NULL)//判定下个结点数据域为空返回递归上一层 
 	return ;
else if(bt->data == a){//判断节点数据与查找的相同则输出层数 
cout <<a<<"所在层数为"<<count<<endl;
b=1;
}
else{//没找到元素继续遍历二叉树 
	if(b==1)//找到了也会遍历后面的元素,利用b==1确定找到了 
	b=1;
	else//不等于1就是没找到 
	b=0;
	find(bt->lchild,count+1,a);
	find(bt->rchild,count+1,a);	
}

}

//主函数
int main()
{
char a;
BiTree T;
CreateBiTree(&T);
getchar();
a = getchar();
find(T,count,a);
if(b==0)
cout<<"0元素在树中不存在"<<endl;
Print(T);

}

猜你喜欢

转载自www.cnblogs.com/ibest/p/12890659.html