数据结构课后作业

来源:互联网 发布:软件外包行业发展趋势 编辑:程序博客网 时间:2024/04/29 18:28

**

要求在采用链式存储结构存储的二叉树上,以bt指向根结点,p指向任一给定的结点,编程实现求出从根节点到给定结点之间的路径。完成此功能需要二叉树的建立,遍历和求最短路径的知识点

**

#include <stdio.h>#include <malloc.h>#include <conio.h>#define S_SIZE 50#define S_MORE 10typedef struct{ int *base;int *top;int ssize;}sqstack;void bs(sqstack &s)//建栈{s.base=(int *)malloc(S_SIZE*sizeof(int));s.top=s.base;s.ssize=S_SIZE;}void push(sqstack &s,int e)//进栈{*s.top++=e;}int pop(sqstack &s)//出栈{   int e;if(s.top!=s.base){e=*--s.top;}return e;}typedef struct BiTree//结点{char data;struct BiTree *lchild,*rchild;}BiTnode,*Bitree;sqstack s1; Bitree CreateBiTree(Bitree &T)//创建结点{    char ch;ch=getch();printf("  ( Y )\n");if(ch==' ') T=NULL;else{T=(Bitree)malloc(sizeof(BiTnode)) ;T->data=ch;CreateBiTree(T->lchild);CreateBiTree(T->rchild);}return T;}void PrinTree(Bitree &T,int &i)//后序遍历的方式遍历出各个叶子结点{ if(T==NULL){ return;}if(T->lchild==NULL&&T->rchild==NULL){printf("-->");printf("%c",T->data);i++;}PrinTree(T->lchild,i);PrinTree(T->rchild,i);}void CouTree(Bitree &T,char p)//根节点到给定结点之间的路径{   if(T==NULL){   pop(s1);return;}    push( s1,T->data);CouTree(T->lchild,p) ;push( s1,T->data);CouTree(T->rchild,p) ;if(T->lchild==NULL&&T->rchild==NULL&&T->data==p) { for(int *p=s1.top;p>=s1.base;p--) { printf("%c",*p); printf("-->"); } printf("\n");}pop(s1);}void main(){   int j=0;char s;Bitree t1;bs(s1);printf("请输入结点数据,空格为空结点!\n");printf("Y为输入的标识符!!!!!!!!\n");t1 = CreateBiTree(t1);if (t1==NULL){printf("该树为空树");}printf("后序遍历的方式遍历出各个叶子结点");PrinTree(t1,j);printf("\n");printf("请输入给定的结点data数据,求出从根节点到给定结点之间的路径!");scanf("%c",&s);CouTree(t1,s);printf("\n");}
0 0