按照网上代码写了一个二叉树创建和遍历
// datastructure.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include "Search.hpp"
typedef struct _BiNode
{
int data;
_BiNode *left;
_BiNode *right;
}BiNode, *PBiNode;
typedef void (*VisitType)(int);
static char s_pEleSet[]="123456789abc";
static char s_pOrder[]="vvvveeveeveevvveevveeveee";
static int s_iCurEle = 0;
static int s_iCurOrder=0;
void PrintNode(int value)
{
printf("current node = %c\n", value);
}
int CreateBinaryTree(PBiNode* pRoot, VisitType func)
{
if(s_pOrder[s_iCurOrder++] == 'e')
*pRoot = NULL;
else
{
*pRoot=(PBiNode)malloc(sizeof(BiNode));
if(NULL != *pRoot )
{
(*pRoot)->data = s_pEleSet[s_iCurEle++];
printf("cur node %c 's leftchild\n",(*pRoot)->data);
CreateBinaryTree(&(*pRoot)->left,func);
printf("cur node %c 's rightchild\n",(*pRoot)->data);
CreateBinaryTree(&(*pRoot)->right,func);
}
}
return 0;
}
//pre-order binaryTree traverse
int PreOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
if(NULL == pRoot)
return 0;
else
{
func(pRoot->data);
PreOrderBinaryTreeTraverse(pRoot->left, func);
PreOrderBinaryTreeTraverse(pRoot->right, func);
}
return 0;
}
//In-order binaryTree traverse
int InOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
if(NULL == pRoot)
return 0;
else
{
InOrderBinaryTreeTraverse(pRoot->left, func);
func(pRoot->data);
InOrderBinaryTreeTraverse(pRoot->right, func);
}
return 0;
}
//post-order binaryTree traverse
int PostOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
if(NULL == pRoot)
return 0;
else
{
PostOrderBinaryTreeTraverse(pRoot->left, func);
PostOrderBinaryTreeTraverse(pRoot->right, func);
func(pRoot->data);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
PBiNode ptree=NULL;
CreateBinaryTree(&ptree, PrintNode);
printf("Pre Order:\n");
PreOrderBinaryTreeTraverse(ptree,PrintNode);
printf("In Order:\n");
InOrderBinaryTreeTraverse(ptree,PrintNode);
printf("Post Order:\n");
PostOrderBinaryTreeTraverse(ptree,PrintNode);
getchar();
return 0;
}