// DataStructTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>

typedef struct btnode * bitreptr;

struct btnode


{
char data; //数据
bitreptr lchild; //左节点指针
bitreptr rchild; //右节点指针
};

//建立一个树,与书中P84中的是一样的,函数返回一个树的头指针
bitreptr CreateTree()


{
bitreptr A,B,C,D,E,F;
bitreptr nodes[6];
for(int i=0;i<6;i++)

{
nodes[i]=(bitreptr)malloc(sizeof(btnode));
nodes[i]->lchild=NULL;
nodes[i]->rchild=NULL;
}
A=nodes[0];
B=nodes[1];
C=nodes[2];
D=nodes[3];
E=nodes[4];
F=nodes[5];

A->data='A';
A->lchild=B;
A->rchild=E;

B->data='B';
B->lchild=C;
B->rchild=D;

C->data='C';

D->data='D';

E->data='E';
E->rchild=F;

F->data='F';

return A;
}

void visit(const bitreptr node)


{
cout<<node->data<<endl;;
}

//先根遍历
void preorder(const bitreptr root)


{
bitreptr node=root;
if (node!=NULL)

{
visit(node);
preorder(node->lchild);
preorder(node->rchild);
}
}
//中根遍历
void inorder(const bitreptr root)


{
bitreptr node=root;
if (node!=NULL)

{
inorder(node->lchild);
visit(node);
inorder(node->rchild);
}
}
//后根遍历
void postorder(const bitreptr root)


{
bitreptr node=root;
if (node!=NULL)

{
postorder(node->lchild);
postorder(node->rchild);
visit(node);
}
}
//计算叶子的数目
void countleaf(const bitreptr t,int & count)


{
if (t!=NULL)

{
if (t->lchild==NULL &&t->rchild==NULL)
count++;
countleaf(t->lchild,count);
countleaf(t->rchild,count);
}
}

int main(int argc, char* argv[])


{
bitreptr root;
//建立树
root=CreateTree();
//
cout<<"先根遍历"<<endl;
preorder(root);
//
cout<<"中根遍历"<<endl;
inorder(root);
//
cout<<"后根遍历"<<endl;
postorder(root);
//
cout<<endl;
int count=0;
countleaf(root,count);
cout<<"页子的数量为:"<<count<<endl;
return 0;
}

一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步