构造一棵二叉树,并分别输出其先序遍历、中序遍历和后序遍历的结果

2024-11-15 13:09:14
推荐回答(2个)
回答1:

#include
using namespace std;

typedef struct BinaryTree
{
char data;
struct BinaryTree *lchild,*rchild;
}BinaryTree,*BiTree;

void CreateBiTree(BiTree &T)
{
char z;
if((z=getchar())==' ')
T=NULL;
else
{
T=(BinaryTree*)malloc(sizeof(BinaryTree));
T->data=z;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
//先序遍历
void preBiTree(BiTree T)
{
if(T!=NULL)
{
cout<data;
preBiTree(T->lchild);
preBiTree(T->rchild);
}
}
//中序遍历
void InBiTree(BiTree T)
{
if(T!=NULL)
{
InBiTree(T->lchild);
cout<data;
InBiTree(T->rchild);
}
}
//后序遍历
void PostBiTree(BiTree T)
{
if(T!=NULL)
{
PostBiTree(T->lchild);
PostBiTree(T->rchild);
cout<data;
}
}
int Depth(BiTree T)
{
if(T==NULL)
{
return 0;
}
else
return 1+(Depth(T->lchild)>Depth(T->rchild)? Depth(T->lchild):Depth(T->rchild));
}

void main()
{
BiTree T;
cout<<"请输入相应二叉树:"< CreateBiTree(T);
cout<悄滚腔<"二叉树的先序遍历为:"< preBiTree(T);
cout< cout<<"二叉树的中序遍历为:"< InBiTree(T);
cout< cout<<"二叉树的后序遍历为:"启衫< PostBiTree(T);
cout< cout<<"二叉树的深度备伍为:"< cout<}

回答2:

#include
#include
#include
int count=0;
typedef struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;

void CreateBiTree(BiTree &T){
int ch;
scanf("%d",&ch);
if(ch==0)T=NULL;
else{
if(!(T=(BiTNode * )malloc(sizeof(BiTNode)))) exit(-1);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int PreOrder(BiTree T)
{
if (!T) return 0;
printf("%d ",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
return 1;
}
int InOrder(BiTree T)
{
if (!T) return 0;

InOrder(T->lchild);
printf("%d ",T->data);
InOrder(T->rchild);
return 1;
}
int PostOrder(BiTree T)
{
if (!T) return 0;

PostOrder(T->lchild);
PostOrder(T->rchild);
printf("%d ",T->data);
return 1;
}
int CountLeaf (BiTree T){

if (!T ) return 0;
if (!T->lchild && !T->rchild) return 1;
int m;
int n;
m = CountLeaf( T->lchild);

n = CountLeaf( T->rchild);

return (m+n);

}

void main(){
int a;
BiTree T;
CreateBiTree(T);
printf("先岁启序乎祥如遍历:");
PreOrder(T);
printf("中序遍历:");
InOrder(T);
printf("后序遍历:");
PostOrder(T);
a=CountLeaf(T);
printf("叶子节宴雀点个数:");
printf("%d",a);
}