建立一棵二叉排序树,统计元素的个数,求代码
答案:1 悬赏:30 手机版
解决时间 2021-05-23 05:21
- 提问者网友:捧腹剧
- 2021-05-22 20:12
建立一棵二叉排序树,统计元素的个数,求C语言程序代码
最佳答案
- 五星知识达人网友:低音帝王
- 2021-05-22 20:21
这是我自己写的:
#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;
}
int Count( node root )
{
int l, r;
if ( root ) {
l = Count( root->l );
r = Count( root->r );
return l + r + 1;
} else {
return 0;
}
}
int main()
{
int a[] = { 6,1,3,5,4,2 };
node root;
root = Create(a, a + 6);
printf( "nodes: %d\n", Count( root ) );
return 0;
}
#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;
}
int Count( node root )
{
int l, r;
if ( root ) {
l = Count( root->l );
r = Count( root->r );
return l + r + 1;
} else {
return 0;
}
}
int main()
{
int a[] = { 6,1,3,5,4,2 };
node root;
root = Create(a, a + 6);
printf( "nodes: %d\n", Count( root ) );
return 0;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯