程序代码:#include <stdio.h>
#include <stdlib.h>
/* BEGIN COPY
*
* Copied from
* http://touch-2011.
*
* 2016-2-12编辑了中序,后序,修改了错误
*/
/* 二叉树的节点定义 */
typedef struct TreeNode
{
char ch; /* 数据域 */
struct TreeNode *lchild; /* 左孩子 */
struct TreeNode *rchild; /* 右孩子 */
}BTNode,*PBTNode;
/* 先序遍历二叉树 */
void preOrder(PBTNode root)
{
if(root==NULL)
return;
printf("%-3c",root->ch);
preOrder(root->lchild);
preOrder(root->rchild);
}
/* 中序遍历二叉树 */
void inOrder(PBTNode root)
{
if(root==NULL)
return;
inOrder(root->lchild);
printf("%-3c",root->ch);
inOrder(root->rchild);
}
/* 后序遍历二叉树 */
void postOrder(PBTNode root)
{
if(root==NULL)
return;
postOrder(root->lchild);
postOrder(root->rchild);
printf("%-3c",root->ch);
}
/* 销毁一颗二叉树 */
void clear(PBTNode* root)
{
PBTNode pl,pr;
if(*root==NULL)
return;
pl=(*root)->lchild;
pr=(*root)->rchild;
(*root)->lchild=NULL;
(*root)->rchild=NULL;
free((*root));
*root=NULL;
clear(&pl);
clear(&pr);
}
/* END COPY */
#define F malloc(sizeof(BTNode))
PBTNode buildTree(char value, PBTNode left, PBTNode right) {
PBTNode n = F;
n->ch = value;
n->lchild = left;
n->rchild = right;
return n;
}
#define buildTreeLeaf(value) buildTree(value, NULL, NULL)
int main(int argc, char const *argv[])
{
/* Build Tree
* From bottom to top
*/
PBTNode root =
buildTree('A',
buildTree('B',
buildTree('D',
buildTreeLeaf('H'),
buildTreeLeaf('I')),
buildTree('E',
buildTreeLeaf('J'),
buildTreeLeaf('K'))),
buildTree('C',
buildTreeLeaf('F'),
buildTreeLeaf('G')));
puts("\nPre-Order:");
preOrder(root);
puts("\nIn-Order:");
inOrder(root);
puts("\nPost-Order:");
postOrder(root);
clear(&root);
return 0;
}[此贴子已经被作者于2016-2-12 12:33编辑过]
