数据结构的二叉树: 要求能够输入树的各个结点,并能够输出用不同方法遍历的遍历序列(具体如下)

论坛 期权论坛 期权     
qianfuliang7   2018-4-26 14:06   9342   1
(1) 建立二叉树存储结构以及编写通过用户输入数据建立二叉树的函数

   (2)输出先序遍历序列的函数

   (3)输出后序遍历序列的函数

    注意: 要完整的能运行的程序、、不要算法   , 最好带一些注释
分享到 :
0 人收藏

1 个回复

倒序浏览
2#
星月and圣冰雨  2级吧友 | 2018-4-30 01:48:34
#include
#include
#include
#include
using namespace std;
typedef int elmtyp;
typedef struct BTnode{
elmtyp data;     //数据域++默认为int
struct BTnode *lch,*rch;
}*BTree,BTnode;

BTree creat()
{
BTree root=NULL;
return root;
}

void insert(BTnode node,elmtyp elm)
{
if(node==NULL) node->data = elm;
else if(node->lch==NULL && node->rch ==NULL) node->data = elm;
else if(elm < node->data)    //在其左子树
{
  insert(node->lch,elm);
}
else if(elm > node->data)   //在其右子树
{
  insert(node->rch,elm);
}
else
{
  return;
}
}

void preorder(BTnode node)    //先序遍历
{
if(node==NULL) return;
printf("%d ",node->data);
preorder(node->lch);
preorder(node->rch);
}

void lastorder(BTnode node)   //后序遍历
{
if(node==NULL) return;
lastorder(node->lch);
lastorder(node->rch);
printf("%d ",node->data);
}

int main()
{
bool end(false);
int cnt(0);
elmtyp data;
BTree root,rootbak;
root = creat();
while(!end)
{
  printf("等待输入第%d个元素,如果输入结束请输入0回车\n",++cnt);
  scanf("%d",&data);
  if(data==0) end = true;
  else
  {
   insert(*root,data);
  }
}
printf("先序遍历\n");
preorder(*rootbak);
printf("\n");
printf("后序遍历\n");
lastorder(*rootbak);
printf("\n");
system("pause");
return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:
帖子:
精华:
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP