数据结构C语言版 二叉树构造算法实验 在键盘上怎么输入

2025-04-27 21:49:15
推荐回答(1个)
回答1:

同学你好:我帮你看了你的程序:这是修改了的程序:希望你能采纳:

这是实验结果:是正确的

 

 

#include "stdio.h"

#include "stdlib.h"

#define OK 1

#define ERROR 0

#define OVERFLOW -2

 

 

typedef char TElemType;

typedef int Status;

typedef struct BiTNode { // 结点结构

    TElemType      data;

    struct BiTNode  *lchild, *rchild; 

                                     // 左右孩子指针

} BiTNode, *BiTree;

 

 

//以下是建立二叉树存储结构

Status CreateBiTree(BiTree &T) {

//请将该算法补充完整,参见第6章课件算法或课本

 char ch;

 scanf(" %c",&ch);

 if(ch=='#') T=NULL;

 else{

  if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))

   exit(OVERFLOW);

  T->data=ch;

  CreateBiTree(T->lchild);

  CreateBiTree(T->rchild);

 }

 return OK;

 

 

} // CreateBiTree

void Preorder(BiTree T)

{

 if(NULL == T)

 {

  return;

 }

 else

 {

  printf("%c",T->data);

  Preorder(T->lchild);

  Preorder(T->rchild);

 }     


 

 

void Inorder(BiTree T)

{ // 中序遍历二叉树 

//请将该算法补充完整,参见第6章课件算法

  if(T)

  {

   Inorder(T->lchild); 

   printf("%c",T->data);

   Inorder(T->rchild);

  }

}

void Postorder(BiTree T)

{ // 后序遍历二叉树 

 //请将该算法补充完整,参见第6章课件算法

 if(T)

 {

  Postorder(T->lchild);

  Postorder(T->rchild);

  printf("%c",T->data);

 }

}

 

 

//以下是求叶子结点数

void CountLeaf(BiTree T,int& count){ 

   //请将该算法补充完整,参见第6章课件算法

 if(T){

  if((!T->lchild)&&(!T->rchild))

   count++;

  CountLeaf(T->lchild,count);

  CountLeaf(T->rchild,count);

 }


 

 

//以下是求二叉树的深度

int Depth(BiTree T ){

      //请将该算法补充完整,参见第6章课件算法

 int depthval,depthLeft,depthRight;

 if(!T)  depthval=0;

 else{

  depthLeft = Depth(T->lchild);

  depthRight = Depth(T->rchild);

  if(depthLeft>depthRight)depthval = 1+depthLeft;

  else depthval = 1+depthRight;

 }

 return depthval;

}

 

 

void main(){

BiTree T;

int s=0,d;

printf("\n creat of the bitree:\n"); 

CreateBiTree(T);

printf("\n output result of Preorder:\n"); 

Preorder(T); 

printf("\n");

 

printf("\n output result of Inorder:\n"); 

Inorder(T);

printf("\n");

 

printf("\n output result of Postorder:\n"); 

Postorder(T);

printf("\n");

 

CountLeaf(T,s);

d=Depth(T);

printf("\n leaves=%d\n",s);

printf("\n depth=%d\n",d);

}