树根结点到r所指结点之间的路径

来源:互联网 发布:谁有x1360的备用域名 编辑:程序博客网 时间:2024/04/27 21:21

#include<stdio.h>/*2009.10.25晚写于白鹿原*/
#include <malloc.h>/*求树根结点到r所指结点之间的路径*/
#include <conio.h>
#define Stack_Size 50
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *LChild;
struct Node *RChild;
}BitNode,*BitTree;
void CreatBiTree(BitTree *bt)//用扩展先序遍历序列创建二叉树,如果是.当前树根置为空,否则申请一个新节点//
{
char ch;
ch=getchar();
if(ch=='.')*bt=NULL;
else
{
*bt=(BitTree)malloc(sizeof(BitNode));
(*bt)->data=ch;
CreatBiTree(&((*bt)->LChild));
CreatBiTree(&((*bt)->RChild));
}
}

void path(BitTree root,BitNode *r)/*根节点到r结点之间的路径并输出*/
{
BitNode *p,*q;
int i,top=0;
BitTree s[Stack_Size];
q=NULL;
p=root;
while(p!=NULL||top!=0)
{
while(p!=NULL)
{
top++;
if(top>=Stack_Size)printf("OverFlow!");
s[top]=p;
p=p->LChild;
}
if(top>0)
{
p=s[top];
if(p->RChild==NULL||p->RChild==q)
{
if(p==r)
{
for(i=1;i<=top;i++)
printf("%c ",s[i]->data);
break;
}
else
{
q=p;
top--;
p=NULL;
}
}
else
p=p->RChild;
}
}
}

void main()
{
BitTree T;
BitNode *p;
printf("请输入二叉树T中的元素(以扩展先序遍历序列输入,其中.代表空子树):/n");
printf("Example (AB.DF..G..C.E.H..)/n");
CreatBiTree(&T);
p=T->LChild->RChild->RChild;
printf("The Path is:");
path(T,p);
}

 

原创粉丝点击