中国科学院大学兰州:急求:数据结构 c语言代码

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/18 10:00:46
给定一棵用二叉链表表示的二叉树,其根指针为root,写出查找值为x的结点的双亲的算法。如无该结点,输出"Not Found"。如有该结点但无双亲,则输出"No parent",如有该结点且有双亲,则输出其双亲的值。

写了一下,你自己再试试吧,我用后序遍历做的:
#include <stdio.h>
#include <stdlib.h>

void PostOrder(TREENODEPTR);
typedef struct treenode
{
int key;
struct treenode *lchild, *rchild;
}TREENODE, *TREENODEPTR;//我的树结点结构,可自己调整
void main()
{
TREENODEPTR root;//这里是给定的root
int x;
scanf("%d",&x);
PostOrder(root,x);
}
void PostOrder(TREENODEPTR troot, int value)
{
TREENODEPTR k , s[20];
int top = 0;
int nodeIsExist = 0;
k = troot;
while(1)
{
while(k != NULL)
{
top++;
s[top] = k;
k = k ->lchild;
}
while(1)
{
if(s[top]->rchild != NULL)
{
k = s[top]->rchild;
break;
}
while(top != 0 && ( k==s[top]->rchild||s[top]->rchild==NULL))
{
k = s[top];
if(k->key == value)
{
nodeIsExist = 1;
if(top != 1)
printf("%d\n",s[top-1]->key);
else
printf("No parent\n");
}
top--;
}
if(top == 0)
{
if(!nodeIsExist)
printf("Not Found\n");
return ;
}
}
}

}

数据结构很难,我到现在也没弄明白