05---二叉树---20195106064---陈昕.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | //输入只有一行,包含一个字符串S,用来建立二叉树。保证S为合法的二叉树先序遍历字符串,节点内容只有大写字母,且S的长度不超过100。 //共一行,包含一串字符,表示按中序遍历二叉线索树得出的节点内容,每个字母后输出一个空格。请注意行尾输出换行。 //例如;ABC DE G F #include<stdio.h> #include<stdlib.h> typedef struct { char ch; }ElemType; typedef enum {Link,Thread} PointerTag; typedef struct BiTNode{ ElemType elem; struct BiTNode *Lchild; struct BiTNode *Rchild; PointerTag LTag; PointerTag RTag; }BiTNode,*BiTree; BiTree pre; void CreatTree(BiTree *T); void InOrderThreading(BiTree *Thrt,BiTree T); void InThreading(BiTree p); void InOrderTraverse(BiTree T); void Z_Traverse(BiTree T); int main() { BiTree T; CreatTree(&T); BiTree Thrt; InOrderThreading(&Thrt,T); //中序线索化 InOrderTraverse(Thrt); //中序遍历 } void CreatTree(BiTree *T) //前序遍历建立二叉树 { char a; scanf ( "%c" ,&a); if (a== ' ' ) { *T=NULL; } else { *T=(BiTree) malloc ( sizeof (BiTNode)); (*T)->elem.ch=a; (*T)->LTag=Link; //初始化 (*T)->RTag=Link; //初始化 CreatTree( &( (*T)->Lchild ) ); CreatTree( &( (*T)->Rchild ) ); } } void InOrderThreading(BiTree *Thrt,BiTree T) { (*Thrt) = (BiTree) malloc ( sizeof (BiTNode)); (*Thrt)->Rchild=*Thrt; //右指针回指 (*Thrt)->RTag=Link; //初始化 if (!T) //如果树是空 左指针也回指 { (*Thrt)->Lchild=*Thrt; (*Thrt)->LTag=Link; } else { pre=*Thrt; (*Thrt)->Lchild=T; (*Thrt)->LTag=Link; InThreading(T); //线索化 pre->Rchild=*Thrt; pre->RTag=Thread; (*Thrt)->Rchild=pre; } } void InThreading(BiTree p) //线索化 { if (p) { InThreading(p->Lchild); if (!p->Lchild) //设置前驱 { p->LTag=Thread; p->Lchild=pre; } if (!pre->Rchild) //设置前一个节点的后继 { pre->RTag=Thread; pre->Rchild=p; } pre=p; InThreading(p->Rchild); } } void InOrderTraverse(BiTree T) //遍历线索化二叉树 { BiTree p; p=T->Lchild; while (p!=T) { while (p->LTag==Link) //找到第一个左孩子为空的节点 { p=p->Lchild; } printf ( "%c " ,p->elem.ch); while (p->RTag==Thread&&p->Rchild!=T) //线索不为空&&不是最后一个节点 { p=p->Rchild; //根据线索遍历 printf ( "%c " ,p->elem.ch); } p=p->Rchild; //转到右子树 } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通