1.该树是基于字符串的二叉树。 2.关键的操作在于传入的参数是指针的指针,即引用传递(切记)。 以下是代码 // Test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <string.h> //二叉树的节点结构体 struct NODE { NODE* pLeft; NODE* pRight; char* word; }; //创建二叉树 void CreateBinaryTree( NODE** pNode, char* szWord ) { if ( NULL == (*pNode) ) { (*pNode) = (NODE*)malloc( sizeof(NODE) ); if ( NULL == (*pNode) ) { printf( "location %s[%d] malloc failure!/n", __FILE__, __LINE__ ); } else { (*pNode)->pLeft = NULL; (*pNode)->pRight = NULL; (*pNode)->word = (char*)malloc( strlen(szWord) + 1 ); if ( NULL == (*pNode)->word) { printf( "location %s[%d] malloc failure!/n", __FILE__, __LINE__ ); } strcpy_s( (*pNode)->word, strlen(szWord) + 1, szWord ); } return; } else { //递归插入到子树 int nFlag = strcmp( (*pNode)->word, szWord ); if ( 0 == nFlag) { return; } else if ( nFlag > 0 ) { CreateBinaryTree( &(*pNode)->pLeft, szWord ); } else { CreateBinaryTree( &(*pNode)->pRight, szWord ); } } } //释放树在开辟过程中释放的空间 void DestroyTree( NODE** root) { if ( *root == NULL ) { return; } else { NODE* pLeftTemp = (*root)->pLeft; NODE* pRightTemp = (*root)->pRight; //释放后,将该指针赋为空 free( ( *root )->word ); ( *root )->word = NULL; //释放后,将该指针赋为空 free( *root ); *root = NULL; //递归释放子树 DestroyTree(&pLeftTemp); DestroyTree(&pRightTemp); } } //将整棵二叉树打印出来,先序遍历 void PrintTreeFirst( NODE** root ) { if ( NULL == (*root) ) { return; } else { printf( "%s/n", (*root)->word ); PrintTreeFirst( &(*root)->pLeft ); PrintTreeFirst( &(*root)->pRight ); } } //将整棵二叉树打印出来,中序遍历 void PrintTreeMid( NODE** root ) { if ( NULL == (*root) ) { return; } else { PrintTreeMid( &(*root)->pLeft ); printf( "%s/n", (*root)->word ); PrintTreeMid( &(*root)->pRight ); } } //将整棵二叉树打印出来,后序遍历 void PrintTreeLast( NODE** root ) { if ( NULL == (*root) ) { return; } else { PrintTreeLast( &(*root)->pLeft ); PrintTreeLast( &(*root)->pRight ); printf( "%s/n", (*root)->word ); } } int main() { NODE* Root = NULL; //创建树的过程,数据从键盘输入 while (1) { char s[10]; gets_s(s); if ( !strcmp(s, "exit") ) { break; } else { CreateBinaryTree( &Root, s); } } //先序遍历树 printf("First Root Search Is Like This/n"); PrintTreeFirst( &Root ); //中序遍历树 printf("Middle Root Search Is Like This/n"); PrintTreeMid( &Root ); //后序遍历树 printf("Last Root Search Is Like This/n"); PrintTreeLast( &Root ); int a = 0; scanf_s("%d",&a); return 0; }