数据结构与算法题目集(中文) 6-9 二叉树的遍历 (25分)
1 // #include <stdio.h> 2 // #include <stdlib.h> 3 4 // typedef char ElementType; 5 // typedef struct TNode *Position; 6 // typedef Position BinTree; 7 // struct TNode{ 8 // ElementType Data; 9 // BinTree Left; 10 // BinTree Right; 11 // }; 12 13 // BinTree CreatBinTree(); /* 实现细节忽略 */ 14 // void InorderTraversal( BinTree BT ); 15 // void PreorderTraversal( BinTree BT ); 16 // void PostorderTraversal( BinTree BT ); 17 // void LevelorderTraversal( BinTree BT ); 18 19 // int main() 20 // { 21 // BinTree BT = CreatBinTree(); 22 // printf("Inorder:"); InorderTraversal(BT); printf("\n"); 23 // printf("Preorder:"); PreorderTraversal(BT); printf("\n"); 24 // printf("Postorder:"); PostorderTraversal(BT); printf("\n"); 25 // printf("Levelorder:"); LevelorderTraversal(BT); printf("\n"); 26 // return 0; 27 // } 28 29 //space + char 30
//中序 31 void InorderTraversal( BinTree BT ) 32 { 33 if (BT) 34 { 35 InorderTraversal( BT->Left); 36 printf(" %c", BT->Data); 37 InorderTraversal( BT->Right); 38 } 39 40 } 41
//前序 42 void PreorderTraversal( BinTree BT ) 43 { 44 45 if (BT) 46 { 47 printf(" %c", BT->Data); 48 PreorderTraversal(BT->Left); 49 PreorderTraversal(BT->Right); 50 } 51 52 }
//后序 53 void PostorderTraversal( BinTree BT) 54 { 55 if (BT) 56 { 57 PostorderTraversal(BT->Left); 58 PostorderTraversal(BT->Right); 59 printf(" %c", BT->Data); 60 } 61 62 63 }
//层遍历 用到队列知识 64 void LevelorderTraversal( BinTree BT ) 65 { 66 67 BinTree qu[2000]; 68 int head = 0, tail = 0; 69 70 if (BT) qu[tail++] = BT; 71 72 while (head < tail) 73 { 74 if(qu[head]->Left) qu[tail++] = qu[head]->Left; 75 if(qu[head]->Right) qu[tail++] = qu[head]->Right; 76 printf(" %c",qu[head++]->Data); 77 } 78 79 80 }
标签:
数据结构和算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!