标签:
#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); }
标签:
原文地址:http://www.cnblogs.com/code-wangjun/p/4637793.html