引言: 数的代码实现, 先序遍历、中序、后序、层次遍历
/* binary_tree.h */
#ifndef _BINARY_TREE_H
#define _BINARY_TREE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEBUG(msg) \
printf("--%s--, %s\n", __func__, msg);
typedef char data_t;
typedef struct node {
data_t data;
struct node *lnext, *rnext;
}bitree_t;
bitree_t *binary_tree_create();
void preorder(bitree_t *r);
void inorder(bitree_t *r);
void postorder(bitree_t *r);
#endif
/* binary_tree.c */
#include "binary_tree.h"
bitree_t *binary_tree_create()
{
char ch;
bitree_t *root = NULL;
scanf("%c", &ch);
if(ch == '#')
return NULL;
root = (bitree_t *)malloc(sizeof(bitree_t));
if(root == NULL) {
DEBUG("malloc failed");
return NULL;
}
root->data = ch;
root->lnext = binary_tree_create();
root->rnext = binary_tree_create();
return root;
}
void preorder(bitree_t *r)
{
if(r == NULL) {
return ;
}
printf("%c ", r->data);
preorder(r->lnext);
preorder(r->rnext);
}
void inorder(bitree_t *r)
{
if(r == NULL) {
return ;
}
inorder(r->lnext);
printf("%c ", r->data);
inorder(r->rnext);
}
void postorder(bitree_t *r)
{
if(r == NULL) {
return ;
}
postorder(r->lnext);
postorder(r->rnext);
printf("%c ", r->data);
}
/* test.c */
#include "binary_tree.h"
int main(int argc, const char *argv[])
{
bitree_t *r;
r = binary_tree_create();
preorder(r);
puts("");
inorder(r);
puts("");
postorder(r);
puts("");
return 0;
}