tree.h
#ifndef _TREE_H_
#define _TREE_H_
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *pL;
struct node *pR;
}BTNode;
extern BTNode *createBinTree();
extern void preOrder(BTNode *pRoot);
extern void inOrder(BTNode *pRoot);
extern void laOrder(BTNode *pRoot);
extern int getNodeNum(BTNode *pRoot);
extern void destroyTree(BTNode *pRoot);
#endif
tree.c
#include "tree.h"
int idx = 0;
char tree[] = {"ABDG###E#H##CF###"};//先序
/*创建二叉树*/
BTNode *createBinTree()
{
BTNode *pNode = NULL;
char ch = tree[idx++];
if(ch == '#')
{
return NULL;
}
else
{
pNode = malloc(sizeof(BTNode));
if(NULL == pNode)
{
perror("fail to createBinTree malloc!\n");
return NULL;
}
pNode->data = ch;
pNode->pL = createBinTree();
pNode->pR = createBinTree();
}
return pNode;
}
/*前序遍历*/
void preOrder(BTNode *pRoot)
{
if(NULL == pRoot)
{
return;
}
printf("%c",pRoot->data);
fflush(stdout);
preOrder(pRoot->pL);
preOrder(pRoot->pR);
}
/*中序遍历*/
void inOrder(BTNode *pRoot)
{
if(NULL == pRoot)
{
return;
}
inOrder(pRoot->pL);
printf("%c",pRoot->data);
inOrder(pRoot->pR);
}
/*后续遍历*/
void laOrder(BTNode *pRoot)
{
if(NULL == pRoot)
{
return;
}
laOrder(pRoot->pL);
laOrder(pRoot->pR);
printf("%c",pRoot->data);
}
/*获取结点数*/
int getNodeNum(BTNode *pRoot)
{
if(NULL == pRoot)
{
return 0;
}
static int num = 0;
getNodeNum(pRoot->pL);
getNodeNum(pRoot->pR);
num++;
return num;
}
/*二叉树的销毁*/
void destroyTree(BTNode *pRoot)
{
if(NULL == pRoot)
{
return;
}
destroyTree(pRoot->pL);
destroyTree(pRoot->pR);
free(pRoot);
}
main.c
#include "tree.h"
int main(int argc, const char *argv[])
{
BTNode *pRoot = NULL;
pRoot = createBinTree();
preOrder(pRoot);
printf("\n");
inOrder(pRoot);
printf("\n");
laOrder(pRoot);
printf("\n");
printf("%d\n",getNodeNum(pRoot));
destroyTree(pRoot);
return 0;
}