程序设计:用递归完成二叉树的遍历(先序,中序,后序,最好有层序)!
答案:2 悬赏:60 手机版
解决时间 2021-05-17 19:10
- 提问者网友:爱唱彩虹
- 2021-05-16 22:11
程序设计:用递归完成二叉树的遍历(先序,中序,后序,最好有层序)!
最佳答案
- 五星知识达人网友:一袍清酒付
- 2021-05-16 23:32
#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(_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;
}
return (p ? v < p->v ? p->l : p->r : *r) = 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) {
postorder(root->l);
postorder(root->r);
printf("%d ", root->v);
}
}
void destruct(node root)
{
if(root) {
destruct(root->l);
destruct(root->r);
free(root);
}
}
int main()
{
int a[] = { 1,2,3,4,5,6 };
node root;
root = create( a, a + 6 );
prevorder( root ); // 前序遍历
putchar( '\n' );
inorder( root ); // 中序遍历
putchar( '\n' );
postorder( root ); // 后续遍历
putchar( '\n' );
destruct( root );
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(_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;
}
return (p ? v < p->v ? p->l : p->r : *r) = 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) {
postorder(root->l);
postorder(root->r);
printf("%d ", root->v);
}
}
void destruct(node root)
{
if(root) {
destruct(root->l);
destruct(root->r);
free(root);
}
}
int main()
{
int a[] = { 1,2,3,4,5,6 };
node root;
root = create( a, a + 6 );
prevorder( root ); // 前序遍历
putchar( '\n' );
inorder( root ); // 中序遍历
putchar( '\n' );
postorder( root ); // 后续遍历
putchar( '\n' );
destruct( root );
return 0;
}
全部回答
- 1楼网友:酒者煙囻
- 2021-05-17 00:45
void preorder (tree_point ptr)
{
if(ptr)
{
printf("%d",ptr->data);
preorder (ptr->left_child);
preorder (ptr->right_child);
}
}
上面的事前序,把printf的位置挪挪就可以变成中序和后序的了。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯