在建树时把叶子节点的左右孩子指针赋为NULL。
然后再递归遍码坦镇历迟粗的时候
void digui(BTree bt)
{
if(bt!=NULL){
printf("%c",bt->data)
digui(bt->rchild)
digui(bt->lchild)
}
else return
}
这样就可以了
#include <stdio.h>#include <malloc.h>
/*定义结构体*/
typedef struct BitTree {
char data
struct BitTree *lchild,*rchild
}BitNode,*BiTree
typedef int status
/*构建树*/
BiTree CreateBiTree(){
BiTree T
char ch
scanf("%c",&ch)
if(ch==' ')T=NULL
else{
T=(BitNode *)malloc(sizeof(BitNode))
T->data=ch
T->lchild=CreateBiTree( )
T->滑判rchild=CreateBiTree( )
}
return T
}
/*遍历输出,先根*/
void PreOrderTraverse(BiTree T){
if(T){
printf("%c",T->data)
PreOrderTraverse(T->lchild)
PreOrderTraverse(T->rchild)
}
}
/*遍历输出,中根*/
void InOrderTraverse(BiTree T){
if(T){
InOrderTraverse(T->橡枣lchild)
printf("%c",T->data)
InOrderTraverse(T->rchild)
}
}
/*遍历输出,后根*/
void PostOrderTraverse(BiTree T){
if(T){
PostOrderTraverse(T->lchild)
PostOrderTraverse(T->rchild)
printf("%c",T->data)
}
}
void main(){
BiTree T
printf("Please input BiTree node with InOeder:"信如改)
T=CreateBiTree()
printf("\nPreOrder is:")
PreOrderTraverse(T)
printf("\nInOeder is:")
InOrderTraverse(T)
printf("\nProstOrder is:")
PostOrderTraverse(T)
printf("\n")
}
A(B C)
(D E) (F G)
以这课树为例
#include <stdio.h>
#include <stdlib.h>
typedef char Elem
typedef struct Node
{
Elem data
struct Node *pLchild
struct Node *pRchild
}BTreeNode, *BTree
BTree CreateBTree(BTree T, Elem *str)//创建二叉树
{
static int i = 0
if ('0' == str[i])
{
T = NULL
}
else
{
T = (BTree) malloc (sizeof(BTreeNode))
T->data = str[i++]
T->pLchild = CreateBTree(T->pLchild, str)
i++
T->pRchild = CreateBTree(T->pRchild, str)
}
return T
}
void PostTraverseBTree(BTree T)//后序
{
if (NULL != T)
{
PostTraverseBTree(T->pLchild)
PostTraverseBTree(T->pRchild)
printf("%c ", T->data)
}
}
void InTraverseBTree(BTree T)//中序
{
if (NULL != T)
{
InTraverseBTree(T->pLchild)
printf("%c ", T->data)
InTraverseBTree(T->pRchild)
}
}
void PreTraverseBTree(BTree T)//先序
{
if (NULL != T)
{
printf("%c ", T->data)
PreTraverseBTree(T->pLchild)
PreTraverseBTree(T->pRchild)
}
}
int main(void)
{
BTree T = NULL
Elem str[] = "ABD00E00CF00G00"
T = CreateBTree(T, str)
printf("\n\n")
printf("先拆返圆序遍历:\n")
PreTraverseBTree(T)
printf("\n\n")
printf("旅塌中序遍历:\n")
InTraverseBTree(T)
printf("\n\n")
printf("后序遍历:\n")
PostTraverseBTree(T)
printf("\n\n"世嫌)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)