码迷,mamicode.com
首页 > 编程语言 > 详细

线索二叉树【C语言】

时间:2015-07-11 01:06:32      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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

typedef  char ElemType;
typedef  enum{Link,Thread} PointerTag; //Link为1,表示连接左孩子;Thread为0,表示连接前继项;

//创建二叉树的结点;
typedef struct BiThrNode
{
    ElemType data;
    BiThrNode *lchild, *rchild;
    PointerTag ltag;
    PointerTag rtag;
}BiThrNode, *BiThrTree;

BiThrTree pre;        //设置一个全局变量,用来存储前继结点的信息;

//创建二叉树,遵循前序遍历;
int CreatBiThrTree(BiThrTree *T)
{
    char c;
    scanf_s("%c", &c);
    if (  == c)
    {
        *T = NULL;
    }
    else
    {
        *T = (BiThrNode *)malloc(sizeof(BiThrNode));
        (*T)->data = c;
        (*T)->ltag = Link;
        (*T)->rtag = Link;
        CreatBiThrTree(&(*T)->lchild);   //采用递归,初始化左孩子,下同;
        CreatBiThrTree(&(*T)->rchild);
    }
    return 1;
}

//创建二叉树线索函数,遵循中序遍历;
int BiThreading(BiThrTree T)
{
    if (T)
    {
        BiThreading(T->lchild);
        if (!T->lchild)
        {
            T->ltag = Thread;
            T->lchild = pre;
        }
        if (!pre->rchild)
        {
            pre->rtag = Thread;
            pre->rchild = T;
        }
        pre = T;
        BiThreading(T->rchild);
    }
    return 1;
}

//创建头结点;
int in_Threading(BiThrTree T, BiThrTree *p)
{
    (*p) = (BiThrNode *)malloc(sizeof(BiThrNode));
    (*p)->ltag = Link;
    (*p)->rtag = Thread;
    (*p)->rchild = *p;
    if (!T)
    {
        (*p)->lchild = *p;
    }
    else 
    {
        (*p)->lchild = T;  
        pre = *p;      //将创建的头结点p赋给pre;
        BiThreading(T);
        pre->rtag = Thread;  //进行收尾工作,形成一个类似于闭合的双向链表;
        pre->rchild = *p;
        (*p)->rchild = pre;
    }
    return 1;
}

//递归方法,二叉树前序遍历;
int Pre_Order_Traverse(BiThrTree T, int level)
{
    printf("递归前序遍历的结果为:\n");
    if (!T)
    {
        return 0;
    }
    else
    {
        printf("第%d层:%c", level, T->data);
        Pre_Order_Traverse(T->lchild, level + 1);    //递归遍历左孩子,下同;
        Pre_Order_Traverse(T->rchild, level + 1);
    }
    return 1;
}

//非递归的方法,二叉树中序遍历,二叉树已存在头结点和线索;
int In_Order_Traverse(BiThrTree T)
{
    if (T)
    {
        BiThrTree P;
        P = T->lchild;
        while (P != T)
        {
            while (P->ltag == Link)
            {
                P= P->lchild;
            }
            printf("%c/n", P->data);
            while (P->rtag == Thread&&P->rchild != T)
            {
                P = P->rchild;
                printf("%c/n", P->data);
            }
            P = P->rchild;
        }
    }
    return 1;
}

//主函数部分;
int main()
{
    int level = 1;
    BiThrTree T,p;
    CreatBiThrTree(&T);
    Pre_Order_Traverse(T, level);
    in_Threading(T, &p);
    In_Order_Traverse(T);
}

 

线索二叉树【C语言】

标签:

原文地址:http://www.cnblogs.com/code-wangjun/p/4637793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!