1.找到特定名字在二叉树中的位置(指针
中序遍历
BTnode *search(BTnode *tree,char _name[20])
{
BTnode* stack[100],*p=tree;
int top=-1;
while (top!=-1)
{
while(p!=NULL)
{
stack[++top]=p;
p=p->lchild;
}
p=stack[top--];
if(strcmp(_name,p->name)==0)
return p;
p=p->rchild;
}
}
完整代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct node
{
char name[100];
int depth;
struct node *lchild,*rchild,*father;
}BTnode;
BTnode* INSERT(char tmp[100])
{
BTnode *p;
p=(BTnode*)malloc(sizeof(BTnode));
strcpy(p->name,tmp);
p->depth=1;
p->lchild=NULL;
p->rchild=NULL;
p->father=NULL;
return p;
}
BTnode *search(BTnode *tree,char _name[20])//中序遍历找名字对应的指针
{
BTnode* stack[200],*p=tree;
int top=-1;
while (!(p==NULL&&top==-1))
{
while(p!=NULL)
{
stack[++top]=p;
p=p->lchild;
}
p=stack[top--];
if(strcmp(_name,p->name)==0)
return p;
p=p->rchild;
}
}
int main()
{
FILE *in;
in=fopen("in.txt","r");
int n,i;
char fa[100],child1[100],child2[100];
fscanf(in,"%d",&n);
fscanf(in,"%s %s %s",fa,child1,child2);
BTnode *tree;
tree=INSERT(fa);
tree->depth=1;
tree->father=NULL;
if(strcmp(child1,"NULL")!=0)
{
BTnode *p;
p=INSERT(child1);
p->father=tree;
tree->lchild=p;
p->depth=2;
}
else
tree->lchild=NULL;
if(strcmp(child2,"NULL")!=0)
{
BTnode *q;
q=INSERT(child2);
q->father=tree;
tree->rchild=q;
q->depth=2;
}
else
tree->rchild=NULL;
for(i=1;i<n;i++)
{
fscanf(in,"%s %s %s",fa,child1,child2);
BTnode *p;
p=(BTnode*)malloc(sizeof(BTnode));
p=search(tree,fa);
if(strcmp(child1,"NULL")!=0)
{
BTnode *a;
a=INSERT(child1);
a->father=p;
p->lchild=a;
a->depth=p->depth+1;
}
else
p->lchild=NULL;
if(strcmp(child2,"NULL")!=0)
{
BTnode *b;
b=INSERT(child2);
b->father=p;
p->rchild=b;
b->depth=p->depth+1;
}
else
p->rchild=NULL;
}
char tmp1[100],tmp2[100];
scanf("%s %s",tmp1,tmp2);
BTnode *t1,*t2;
t1=search(tree,tmp1);
t2=search(tree,tmp2);
if(t1->depth==t2->depth)
{
BTnode *p,*q;
p=t1;
q=t2;
while(p!=NULL&&q!=NULL)
{
if(p==q)
break;
p=p->father;
q=q->father;
}
printf("%s %s %d\n",p->name,t1->name,t1->depth-p->depth);
printf("%s %s %d",p->name,t2->name,t2->depth-p->depth);
}
else if(t1->depth < t2->depth)
printf("%s %s %d",t2->name,t1->name,t2->depth-t1->depth);
else
printf("%s %s %d",t1->name,t2->name,t1->depth-t2->depth);
fclose(in);
return 0 ;
}