第一种表示方法:
双亲数组表示法,第0号不存数据,从第1号开始存放。
子女—兄弟表示法
tree.h
#ifndef TREE_H
#define TREE_H
typedef char ElemType;
typedef struct TreeNode
{
ElemType data;
TreeNode * firstNode;
TreeNode * nextSibling;
}TreeNode ,*Tree;
TreeNode * FindValue(TreeNode *ptr,ElemType x);
TreeNode * FindParent(TreeNode *ptr,ElemType x);
TreeNode * MakeRoot(ElemType x);
TreeNode * InsertChild(TreeNode *ptr,ElemType x);
TreeNode * InsertSib(TreeNode *ptr,ElemType x);
#endif
Tree.cpp
#include <tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
TreeNode * FindValue(TreeNode *ptr,ElemType x)
{
if(ptr == NULL || ptr->data == x)
{
return ptr;
}
else{
TreeNode *p = ptr->firstchild;
TreeNode *res = NULL;
while(p != NULL && (res = FindValue(p,x)) == NULL)
{//如果有左孩子而且左孩子的分支里未找到
p = p->nextSibling;
}
return res;
}
}
TreeNode * FindParent(TreeNode *ptr,ElemType x)
{
if(ptr == NULL || child== NULL || ptr==child)
{
return ptr;
}else
{
return Parent(ptr,child);
}
}
TreeNode * Parent(TreeNode *ptr,ElemType x)
{
if(ptr == NULL ) return ptr;
TreeNode *p = ptr->firstchild;
TreeNode *tmp = p;
while(p != NULL && p != child)
{//如果 p 不为空 p不等于孩子
TreeNode *res = Parent(p,child); //在 左孩子结点找 child 的返回值
if(res != NULL) return res; //找到了
p = p->nextSibling;//没找到 在兄弟结点找
}
if(p!=NULL) // 找到child了
{
return ptr;
}else // p==NULL
{
return NULL;
}
}
TreeNode *BuyNOde()
{
TreeNode *s = (TreeNode *)malloc(sizeof(TreeNode));
assert(s != NULL);
s->firstchild = NULL;
s->nextSibling = NULL;
return s;
}
TreeNode *MakeRoot(ElemType x)
{
TreeNode *root = BuyNode();
root->data = x;
return root;
}
TreeNode * InsertChild(TreeNode *ptr,Elemtype x)
{
if(ptr == NULL)
{
return ptr;
}
TreeNode *s = BuyNode();
s->data = x;
if(ptr->firstchild == NULL)
{
ptr->firstchild = s;
}else
{
TreeNode *p = NULL;
p=ptr->firstchild;
while(p->nextSibling != NULL)
{
p=p->nextSibling;
}
p->nextSibling = s;
}
return s;
}
TreeNode * InsertSib(TreeNode *ptr,Elemtype x)
{
if(ptr == NULL)
{
return ptr;
}
TreeNode * s = BuyNode();
s->data = x;
while(ptr->nextSibling != NULL)
{
ptr = ptr->nextSibling;
}
ptr->nextSibling = s;
return s;
}
void main()
{
Tree root = NULL;
root = MakeRoot('A');
TreeNode *bp = InsertChild(root,'B');
InsertChild(bp,'E');
InsertChild(bp,'F');
TreeNode *cp = InsertChild(root,'C');
TreeNode *gp=InsertChild(cp,'G');
InsertChild(gp,'K');
InsertChild(gp,'L');
TreeNode *dp = InsertChild(root,'D');
InsertChild(dp,'H');
InsertChild(dp,'I');
TreeNode *jp =InsertChild(dp,'J');
InsertChild(jp,'M');
Elemtype ar[] = {"ABCDEFGHIJKLMNOP"};
int n = strlen(ar);
for(int i = 0;i<n;++i)
{
TreeNode *p = FindValue(root,ar[i]);
if(p!=NULL)
{
printf("%x==%c\n",p,p->data);
TreeNode *pa = FindParent(root,p);
if(pa != NULL)
{
printf("%c => parent:%c\n",p->data,pa->data);
}else
{
printf("no parents\n");
}
}
else
{
printf("not find value.\n");
}
}
}
测试结果: