//树和森林
#include <stdlib.h>
#include <stdio.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef struct TNode{//树的二叉链表
int id; //树的身份
int data;
//树的第一个孩子 树的兄弟节点 树的父节点
struct TNode *FristChild,*NextSibiling,*parent;
}TNode,*PTree;
Status InitTree(PTree *PT,int id,int data)
{//初始化 树
if(!((*PT)=(PTree)malloc(sizeof(TNode)))) return ERROR;
(*PT)->id=id; (*PT)->data=data;
;
(*PT)->FristChild=NULL;
(*PT)->NextSibiling=NULL;
(*PT)->parent=NULL;
return OK;
}
Status FindNodeById(const PTree T,PTree *PT,int id)
{//寻找 树节点
if(T)
{
if(T->id==id)
{ (*PT)=T; }
FindNodeById(T->FristChild,PT,id);
FindNodeById(T->NextSibiling,PT,id);
return OK;
}else{return ERROR;}
}
Status InsertTree(PTree Tr,int fid,int sid,int data,int type,int num)
{//type 为成为该fid节点的 孩子节点或者兄弟节点 0为孩子 1为兄弟 num为该fid节点后第几个前插入
//如果num超出 兄弟节点的最大值 则在最后一个插入
PTree N=NULL,Na; //Na为前节点
PTree T;
int i,j;
if(FindNodeById(Tr,&N,fid) && N)
{
if(!((T)=(PTree)malloc(sizeof(TNode)))) return ERROR;
T->id=sid; T->data=data; T->FristChild=NULL;
if(type)
{
for(i=1;i<num && N->NextSibiling;i++,N=N->NextSibiling);
T->parent=N->parent;
T->NextSibiling=N->NextSibiling;
N->NextSibiling=T;
}else{
for(Na=N->FristChild,i=2;i<num && Na->NextSibiling;i++,Na=Na->NextSibiling);
T->parent=N;
if(num==1 || !N->FristChild)
{//首节点 或 第一个节点为空
T->NextSibiling=N->FristChild;
N->FristChild=T;
}else{
T->NextSibiling=Na->NextSibiling;
Na->NextSibiling=T;
}
}
return OK;
}else{return ERROR;}
}
Status GetParent(const PTree T,PTree *PT)
{
if(!T) return ERROR;
(*PT)=T->parent;
return OK;
}
Status TraverseTree(const PTree T)
{//遍历树
if(T)
{
printf(" id:%d data:%d ",T->id,T->data); //先序
TraverseTree(T->FristChild);
// printf(" id:%d data:%d ",T->id,T->data);
TraverseTree(T->NextSibiling);
return OK;
}else{return ERROR;}
}
Status DestoryTree(PTree *T)
{
if(*T)
{
DestoryTree(&(*T)->FristChild);
DestoryTree(&(*T)->NextSibiling);
free(*T); (*T)=NULL;
return OK;
}
}
int main()
{
PTree T,R,G;
InitTree(&T,1,12);
InsertTree(T,1,2,22,0,1);
InsertTree(T,1,3,23,0,2);
InsertTree(T,1,4,24,0,3);
InsertTree(T,1,5,24,0,4);
InsertTree(T,2,6,12,0,1);
InsertTree(T,2,7,22,0,2);
InsertTree(T,3,8,13,0,1);
FindNodeById(T,&R,7);
GetParent(R,&G);
printf(" parent: id:%d data:%d \n",G->id,G->data);
TraverseTree(T);
DestoryTree(&T);
TraverseTree(T);
}