二叉树的遍历

数据结构实验

先序创建二叉树,先序遍历,中序遍历,后序遍历。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char Elemtype;
typedef struct BiTNode
{
    Elemtype data;
    struct BiTNode *lchild, *rchild;
}BiTNode;
typedef BiTNode * BiTree;
BiTree CreateBiTree()
{
    char ch;
    BiTree T;
    scanf("%c",&ch);
    if(ch == '#') T = NULL;
    else
    {
        T = (BiTree )malloc (sizeof(BiTNode ));
        if(!T) exit(1);
        else
        {
            T->data = ch;
            T->lchild = CreateBiTree();
            T->rchild = CreateBiTree();
        }
    }
    return T;
}
void PreOrder(BiTree root)
{
    if(root == NULL) return  ;
    printf("%c", root->data);
    PreOrder( root->lchild );
    PreOrder( root->rchild );
}
void InOrder(BiTree root)
{
    if(root == NULL) return  ;
    InOrder( root->lchild );
    printf("%c", root->data);
    InOrder( root->rchild );
}
void PostOrder(BiTree root)
{
    if(root == NULL) return  ;
    PostOrder( root->lchild );
    PostOrder( root->rchild );
    printf("%c", root->data);
}
int main()
{
	printf("1.建立二叉树\n");
	printf("2.先序遍历二叉树\n");
	printf("3.中序遍历二叉树\n");
	printf("4.后序遍历二叉树\n");
    printf("请选择:");
	BiTree T;
	T = (BiTree )malloc(sizeof(BiTNode ));
	int a;
	while(scanf("%d\n",&a),a)
	{
		if(a==1)
		{
			T = CreateBiTree();
			printf("建立成功,执行遍历选项:\n");
		}
		else if(a==2)
		{
			T = CreateBiTree();
			printf("前序遍历:\n");
			PreOrder(T);
			printf("\n");
		}
		else if(a==3)
		{
			T = CreateBiTree();
			printf("中序遍历:\n");
			InOrder(T);
			printf("\n");
		}
		else if(a==4)
		{
			T = CreateBiTree();
			printf("后序遍历:\n");
			PostOrder(T);
			printf("\n");
		}
	}
	return 0;
}

/*
  测试数据:AB#EG##H##CF###
  先序遍历:ABEGHCF
  中序遍历:BGHEAFC
  后序遍历:GHEBFCA
*/



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值