#include<stdio.h>
#include<stdlib.h>
struct treeNode
{
int data;
struct treeNode* leftPtr;
struct treeNode* rightPtr;
};
typedef struct treeNode TreeNode;
typedef TreeNode* TreeNodePtr;
void insertNode( TreeNodePtr* treePtr, int value );
void inOrder( TreeNodePtr treePtr );
void preOrder( TreeNodePtr treePtr );
void postOrder( TreeNodePtr treePtr );
void deleteTree( TreeNodePtr* treePtr );
int main()
{
int i;/* 计数器 1~7 */
int item;
TreeNodePtr treePtr=NULL;
for ( i=1; i<=7; ++i )
{
printf( "please enter an integer:" );
scanf( "%d", &item );
insertNode( &treePtr, item );
}
printf( "inOrder:" );
inOrder( treePtr );
printf( "/n" );
printf( "preOrder:" );
preOrder( treePtr );
printf( "/n" );
printf( "postOrder:" );
postOrder( treePtr );
printf( "/n" );
deleteTree( &treePtr );
return 0;
}
void insertNode( TreeNodePtr* treePtr, int value )
{
/* 把数据插入到空节点中 */
if ( *treePtr == NULL )
{
*treePtr=(TreeNodePtr)malloc( sizeof(TreeNode) );
/* 分配空间成功 */
if ( *treePtr != NULL )
{
(*treePtr)->data=value;
(*treePtr)->leftPtr=NULL;
(*treePtr)->rightPtr=NULL;
}
}
else /* 节点不为空 */
{
if ( (*treePtr)->data > value )
{ /* 利用递归将数据插入到左子节点中 */
insertNode( &( (*treePtr)->leftPtr ), value );
}
else if ( (*treePtr)->data < value )
{
/* 利用递归将数据插入到右子节点中 */
insertNode( &( (*treePtr)->rightPtr ), value );
}
else /* 忽略重复的值 */
printf( "dup" );
}
}
/* 中序遍历 */
void inOrder( TreeNodePtr treePtr )
{
if ( treePtr == NULL )
return;
inOrder( treePtr->leftPtr );
printf( "%d/t", treePtr->data );
inOrder( treePtr->rightPtr );
}
/* 前序遍历 */
void preOrder( TreeNodePtr treePtr )
{
if ( treePtr == NULL )
return;
printf( "%d/t", treePtr->data );
preOrder( treePtr->leftPtr );
preOrder( treePtr->rightPtr );
}
/* 后序遍历 */
void postOrder( TreeNodePtr treePtr )
{
if ( treePtr == NULL )
return;
postOrder( treePtr->leftPtr );
postOrder( treePtr->rightPtr );
printf( "%d/t", treePtr->data );
}
void deleteTree( TreeNodePtr* treePtr )
{
if ( *treePtr == NULL )
return;
/* 先删除左子树 */
deleteTree( &( (*treePtr)->leftPtr ) );
/* 再删除右子树 */
deleteTree( &( (*treePtr)->rightPtr ) );
/* 最后删除树根 */
free( (*treePtr) );
}