二叉树建立与遍历

本算法主要是利用扩展先序遍历法创建二叉树,再用先序遍历遍历二叉树,最后按照树形输出整个二叉树:

关于本文中的扩展先序遍历法,可参照:

http://baike.baidu.com/view/5050145.htm

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef int DataType;

typedef struct Node {
    DataType data;
    struct Node *LChild;
    struct Node *RChild;
}BiNode,*BiTree;

void CreateBiTree(BiTree *bt) //扩展先序遍历法建造BiTree
{
    char ch;
    ch = getchar();
    if ('.' == ch)
        *bt = NULL;
    else
    {
        *bt = (BiTree)malloc(sizeof(BiNode));
        (*bt)->data = ch;
        CreateBiTree(&((*bt)->LChild));
        CreateBiTree(&((*bt)->RChild));
    }
}//CreateBitTree

void Visit(char ch)  //单个输出
{
    printf("%c ",ch);
}//Visit

void PreOrder(BiTree root)  //先序遍历
{
    if (NULL != root)
    {
        Visit(root->data);
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
} //PreOrder

void PrintTree(BiTree Boot,int nLayer) //打印二叉树
{
    int i;
    if (NULL == Boot)
        return;
    PrintTree(Boot->RChild,nLayer+1);
    for (i=0; i<nLayer; ++i)
    {
        printf(" ");
    }
    printf("%c\n",Boot->data);
    PrintTree(Boot->LChild,nLayer+1);
} //PrintTree

int main()
{
    BiTree T;
    int layer = 0;
    printf("以扩展先序遍历序列输入,其中.代表空子树:\n");
    CreateBiTree(&T);
    printf("PreOrder:");
    PreOrder(T);
    printf("\n");
    PrintTree(T,layer);
    return 0;
}  //main

实例结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值