6-2 二叉树的遍历 (25分)
2020-03-26 08:11
113 查看
本题要求给定二叉树的4种遍历。
函数接口定义:
void InorderTraversal( BinTree BT ); void PreorderTraversal( BinTree BT ); void PostorderTraversal( BinTree BT ); void LevelorderTraversal( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; };
要求4个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; BinTree CreatBinTree(); /* 实现细节忽略 */ void InorderTraversal( BinTree BT ); void PreorderTraversal( BinTree BT ); void PostorderTraversal( BinTree BT ); void LevelorderTraversal( BinTree BT ); int main() { BinTree BT = CreatBinTree(); printf("Inorder:"); InorderTraversal(BT); printf("\n"); printf("Preorder:"); PreorderTraversal(BT); printf("\n"); printf("Postorder:"); PostorderTraversal(BT); printf("\n"); printf("Levelorder:"); LevelorderTraversal(BT); printf("\n"); return 0; } /* 你的代码将被嵌在这里 */
输出样例(对于图中给出的树):
Inorder: D B E F A G H C I Preorder: A B D F E C G H I Postorder: D E F B H G I C A Levelorder: A B C D F G I E H
几点要注意的:
- 这种题不给你建树函数的可以自己写一个简化的, 像这样
BinTree CreatBinTree() { BinTree BT = (BinTree)malloc(sizeof(TNode)); BT->Data = 'A'; BT->Left = (BinTree)malloc(sizeof(TNode)); BT->Left->Data = 'B'; BT->Left->Left = (BinTree)malloc(sizeof(TNode)); BT->Left->Left->Data = 'D'; BT->Left->Left->Left = NULL; BT->Left->Left->Right = NULL; BT->Left->Right = (BinTree)malloc(sizeof(TNode)); BT->Left->Right->Data = 'F'; BT->Left->Right->Right = NULL; BT->Left->Right->Left = (BinTree)malloc(sizeof(TNode)); BT->Left->Right->Left->Data = 'E'; BT->Left->Right->Left->Left = NULL; BT->Left->Right->Left->Right = NULL; BT->Right = (BinTree)malloc(sizeof(TNode)); BT->Right->Data = 'C'; BT->Right->Left = NULL; BT->Right->Right = NULL; return BT; }
- 只要写递归, 一定先写边界条件
- 复制粘贴函数内容的话记得把引用函数改回去, 别三种遍历函数里引用的函数都是中序遍历函数
层次遍历
前三种遍历都比较简单, 各四行就完事, 层次遍历稍复杂. 如果树是用数组存储, 层次遍历就顺着把数组输出来就行了, 指针树的话要加一个队列.
- 1.建个BinTree数组一个对头int一个队尾int (建队列)
- 2.先把树根节点加进队列
- 3.每个循环处理当前对头节点, 把对头节点的左右子节点加到队尾并输出队头节点Data, 对头节点出队
- 4.直到对头int==队尾int结束循环
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 4-9 二叉树的遍历 (25分)
- 【PTA 5-10 树的遍历 (25分)】+ 二叉树
- 4-9 二叉树的遍历 (25分)
- PTA数据结构与算法题目集(中文)4-9 二叉树的遍历 (25分)
- 6-9 二叉树的遍历 (25分)
- 4-9 二叉树的遍历 (25分)(前、中、后、层次)
- 4-9 二叉树的遍历 (25分)
- 4-9 二叉树的遍历 (25分)
- 数据结构与算法题目集(中文)4-9 二叉树的遍历 (25分)
- PTA 6-2 二叉树的遍历(25 分) 25分代码 (数组实现层次遍历)
- 1020 Tree Traversals (25分)、1086 Tree Traversals Again (25分)、1102 Invert a Binary Tree (25分)练习二叉树的遍历
- 非递归遍历二叉树
- day09之N的阶乘N!末尾有多少个0 + 二叉树的层序遍历
- java实现二叉树的构建以及3种遍历方法
- 层次遍历二叉树
- 先序、中序、后序遍历二叉树及二叉搜索树的总结
- 二叉树的层序遍历(非递归,借用队列实现)
- 【详解】前、中、后序线索化二叉树及其遍历
- 【C】二叉树的遍历
- 二叉树先序、中序、后序遍历的非递归实现