#include <stdio.h>
#include <stdlib.h>
typedef struct tree{
char data;
struct tree*firstchild;
struct tree*nextbrother;
}tree;
tree*build(tree*root){
char k;
scanf("%c",&k);
if(k=='#'){
root=NULL;
}
else{
root=(tree*)malloc(sizeof(tree));
root->data=k;
root->firstchild=build(root->firstchild);
root->nextbrother=build(root->nextbrother);
}
return root;
}
tree*GFC(tree*p){//树找特定节点的大儿子
if(p!=NULL&&p->firstchild!=NULL)
return p->firstchild;
return NULL;
}
tree*GNB(tree*p){//找特定节点的右兄弟
if(p!=NULL&&p->nextbrother!=NULL)
return p->nextbrother;
return NULL;
}
void preorder(tree*root){//树的先根遍历序列(递归)
if(root==NULL)
return;
printf("%c\t",root->data);
tree*p=GFC(root);
while(p!=NULL){
preorder(p);
p=GNB(p);
}
}
void pre_order(tree*root){//树的非递归先根遍历(辅助堆栈)
tree*s[20];//创建栈
int i=-1;
tree*p=root;
while(i!=-1||p){
while(p!=NULL)
{
printf("%c\t",p->data);//打印
s[++i]=p;//节点入栈
p=GFC(p);//取大儿子
}
/*p=s[i];//节点出栈
i--;
p=GNB(p);//取右兄弟*///未优化版本
while(p==NULL&&i!=-1){
p=s[i];
i--;
p=GNB(p);
}//优化后(其实不优化也行,与二叉树的非递归先根遍历保持一致)
}
}
void levelorder(tree*root){//树的层次遍历(辅助环状队列)
tree*s[20];//创建环状队列
int top=0,tail=0,count=0;
int i=0;
s[tail]=root;//队尾插入
tail=(tail+1)%20;
count++;
tree*p;
while(count!=0){
p=s[top];//节点出队(对头出队)
top=(top+1)%20;
count--;
while(p!=NULL){
printf("%c\t",p->data);
if(GFC(p)!=NULL)//只需将每个节点的大儿子入队即可
{s[tail]=GFC(p);
tail=(tail+1)%20;
count++;}
p=p->nextbrother;//接着对大儿子的右兄弟做单链表的遍历即可
}
}
}
tree*find(tree*root,char target){//找值为target的指定节点(递归)
tree*result=NULL;
if(root==NULL)
return NULL;
if(root->data==target)
return root;
tree*p;
p=GFC(root);
while(p!=NULL){
result=find(p,target);
if(result!=NULL)
return result;
else p=GNB(p);//一棵一棵子树的寻找
}
}
tree*findfather(tree*root,tree*p){//寻找特定节点的父亲(递归)
tree*result=NULL;
if(root==NULL||p==NULL)
return NULL;
if(root==p)
return NULL;
tree*q;
q=GFC(root);
while(q!=NULL&&q!=p){
result=findfather(q,p);
if(result!=NULL)
return result;
q=GNB(q);
}
if(p==q)
return root;
else return NULL;
}
void del(tree*p){//释放节点为p的子树(递归)
if(p==NULL)
return;
tree*next;
tree*q=p->firstchild;
while(q!=NULL){
next=q->nextbrother;
del(q);
q=next;
}
free(q);
}
void DS(tree*root,tree*p){//删除特定节点的子树
if(root==NULL||p==NULL)
return;
tree*result=findfather(root,p);
if(result==NULL)//要删除节点为根节点
{del(p);
return;
}
if(result->firstchild==p){//要删除节点为为某节点的大儿子
result->firstchild=p->nextbrother;
del(p);
return;
}
tree*q;
q=result->firstchild;
while(q->nextbrother!=p){//要删除节点为某节点的右兄弟
q=q->nextbrother;}
q->nextbrother=p->nextbrother;
del(p);
}
int main()
{ char k;
tree*root,*p;
root=build(root);
getchar();
printf("请输入目标值:");
scanf("%c",&k);
//preorder(root);
//printf("\n");
//pre_order(root);
//printf("\n");
printf("层次遍历结果为:");
levelorder(root);
p=find(root,k);
printf("\n");
if(p!=NULL)
printf("找到了值为目标值的节点:%c\t\n",p->data);
else
printf("没有找到值为目标值的节点\n");
tree*q=NULL;
if(p!=NULL)
{q=findfather(root,p);
if(q!=NULL)
printf("找到了值为目标值的节点的父亲:%c\t\n",q->data);
else
printf("值为目标值的节点没有父亲\n");
}
DS(root,p);
levelorder(root);
return 0;
}//abe#f#g##chmn####di#j#k#l####//测试数据