建立二叉链表并先序 中序 后序的c程序
答案:1 悬赏:20 手机版
解决时间 2021-04-22 19:15
- 提问者网友:疯子也有疯子的情调
- 2021-04-22 02:33
数据结构
最佳答案
- 五星知识达人网友:孤独的牧羊人
- 2021-04-22 03:44
#include <stdio.h>
#include <stdlib.h>
typedef struct _btree {
int v;
struct _btree* l;
struct _btree* r;
}**btree, *node;
node Insert(btree r, int v)
{
node t, p, n;
t = (node)malloc(sizeof(struct _btree)) ;
t->v = v;
t->l = t->r = NULL;
p = NULL, n = *r;
while(n) {
p = n;
n = v < n->v ? n->l : n->r;
}
if (p) {
if (v < p->v) {
p->l = t;
} else {
p->r = t;
}
} else {
*r = t;
}
return t;
}
node Create(int* beg, int* end)
{
node root;
root = NULL;
while(beg != end)
Insert(&root, *beg++);
return root;
}
void Prevorder(node root)
{
if(root) {
printf("%d ", root->v);
Prevorder(root->l);
Prevorder(root->r);
}
}
void Inorder(node root)
{
if(root) {
Inorder(root->l);
printf("%d ", root->v);
Inorder(root->r);
}
}
void Postorder(node root)
{
if(root) {
printf("%d ", root->v);
Postorder(root->r);
Postorder(root->l);
}
}
void Destruct(node root)
{
if(root) {
Destruct(root->l);
Destruct(root->r);
free(root);
}
}
int main()
{
int a[] = { 6,1,3,5,4,2 };
node root;
root = Create(a, a + 6);
Prevorder(root);
putchar('\n');
Inorder(root);
putchar('\n');
Postorder(root);
putchar('\n');
Destruct(root);
getchar();
return 0;
}
附图:
#include <stdlib.h>
typedef struct _btree {
int v;
struct _btree* l;
struct _btree* r;
}**btree, *node;
node Insert(btree r, int v)
{
node t, p, n;
t = (node)malloc(sizeof(struct _btree)) ;
t->v = v;
t->l = t->r = NULL;
p = NULL, n = *r;
while(n) {
p = n;
n = v < n->v ? n->l : n->r;
}
if (p) {
if (v < p->v) {
p->l = t;
} else {
p->r = t;
}
} else {
*r = t;
}
return t;
}
node Create(int* beg, int* end)
{
node root;
root = NULL;
while(beg != end)
Insert(&root, *beg++);
return root;
}
void Prevorder(node root)
{
if(root) {
printf("%d ", root->v);
Prevorder(root->l);
Prevorder(root->r);
}
}
void Inorder(node root)
{
if(root) {
Inorder(root->l);
printf("%d ", root->v);
Inorder(root->r);
}
}
void Postorder(node root)
{
if(root) {
printf("%d ", root->v);
Postorder(root->r);
Postorder(root->l);
}
}
void Destruct(node root)
{
if(root) {
Destruct(root->l);
Destruct(root->r);
free(root);
}
}
int main()
{
int a[] = { 6,1,3,5,4,2 };
node root;
root = Create(a, a + 6);
Prevorder(root);
putchar('\n');
Inorder(root);
putchar('\n');
Postorder(root);
putchar('\n');
Destruct(root);
getchar();
return 0;
}
附图:
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯