09级数据结构课程设计程序源代码
#include \"stdio.h\" #include \"stdlib.h\" #define num 100 #define TRUE
1 #define FALSE
0 #define OK
1 #define ERROR
0 #define OVERFLOW
-2 #define RIGHT
1 #define LEFT
0
typedef int Status; typedef char DataType; int found;
typedef struct node{ DataType data; struct node *lchild,*rchild; }BinTNode,*BinTree; BinTNode *p;
int CreateBiTree(BinTree *bt) { char ch; scanf(\"%c\",&ch); if(ch==\'@\')
(*bt)=NULL; else {
(*bt)=(BinTNode *)malloc(sizeof(BinTNode));
if(!(*bt))
return ERROR;
(*bt)->data=ch;
CreateBiTree(&(*bt)->lchild);
CreateBiTree(&(*bt)->rchild); } return OK; }
int Inorder(BinTree &bt)/{ BinTNode *stack[num]; //定义栈数组
int top=0; //初始化栈
stack[top]=bt; do {
while(NULL!=stack[top])
{ //扫描根结点及其所有的左结点并入栈
top=top+1;
stack[top]=stack[top-1]->lchild;
}
top=top-1; //退栈
if(top>=0) //判断栈是否为空
{
printf(\"%c\",stack[top]->data); //访问结点
stack[top]=stack[top]->rchild; //扫描右子树
} }while(top>=0); return OK; }//Inorder
int Depth(BinTree bt)//求二叉树的深度 { int h,lh,rh; if(!bt)h=0; else {
lh=Depth(bt->lchild);
rh=Depth(bt->rchild);
if(lh>=rh)
h=lh+1;
else
h=rh+1; } return h; } int LeafCount(BinTree bt)//5.求叶子节点的个数 { if(!bt) return 0; //空树没有叶子
else if(!bt->lchild&&!bt->rchild) return 1; //叶子结点
else return LeafCount(bt->lchild)+LeafCount(bt->rchild); }//LeafCount
int
Exchange(BinTree *bt) { BinTNode *temp; if((*bt)==NULL)
return ERROR; else {
temp=(*bt)->lchild;
(*bt)->lchild=(*bt)->rchild;
(*bt)->rchild=temp; } Exchange(&(*bt)->lchild); Exchange(&(*bt)->rchild); return OK; }
void main() { BinTree bt; int xz=1; char ch; BinTree tree; while(xz) { printf(\" 建立二叉树并求指定结点路径\\n\"); printf(\"===========================\\n\"); printf(\" 1.建立二叉树的存储结构\\n\"); printf(\" 2.求解二叉树的中序遍历\\n\"); printf(\" 3.求二叉树指定节点的路径\\n\"); printf(\" 4.求二叉树的深度\\n\"); printf(\" 5.求二叉树的叶子节点个数\\n\"); printf(\" 6.将二叉树左右子树交换\\n\");
printf(\" 0.退出系统\\n\"); printf(\"===========================\\n\"); printf(\" 请选择:(0-6) \\n\"); scanf(\"%d\",&xz); getchar(); switch(xz) {
case 0:break; case 1:printf(\"输入二叉树的先序序列结点值:\\n\");
CreateBiTree(&tree);
getchar();
printf(\"二叉树的链式存储结构建立完成! \\n\");
break; case 2:printf(\"该二叉树的中序遍历序列是:\\n\");
Inorder(tree);printf(\"\\n\");
break; case 3:
printf(\"输入要求路径的结点值:\");
scanf(\"%c\",&ch);
getchar();
FindNodePath(tree,ch);
break; case 4:printf(\"该二叉树的深度为:%d\\n\",Depth(tree));
printf(\"\\n\");
break; case 5:printf(\"该二叉树的叶子结点个数为:%d\\n\",LeafCount(tree));
printf(\"\\n\");
break; case 6:
Exchange(&tree);
printf(\"该二叉树的左右结点已交换成功,其中序遍历序列是:\");
Inorder(tree);
printf(\"\\n\");
break;
} }