《数据结构与算法A》实验4:二叉树基本操作的实现
Description
建立二叉树的顺序存储结构,掌握二叉树的递归遍历算法与非递归算法,实现以下基本操作:
(1) 建立二叉树的顺序存储;
(2) 前序(递归)遍历树;
(3)中序(非递归)遍历树;
(4)后序(递归)遍历树。
顺序存储结构实现的二叉树参考代码如下:
const int MaxBinarySize=100; //根据问题修改该值
class SeqBinaryTree{
int data[MaxBinarySize]; //存储字符串
int size; //二叉树结点个数
public:
SeqBinaryTree( ); //构造函数
void CreateBianryTree( ); //创建二叉树
void PreOrder(int root=1); //前序遍历,递归算法
void InOrder(int root=1); //中序遍历,非递归算法
void PostOrder(int root=1); //后序遍历,递归算法
}; //SeqBinaryTree
Input
本题目包含多组测试数据。每组数据有两行,第一行是一个正整数n(1≤n<200),表示二叉树中结点个数;第二行是以空格间隔的n个整数,根据该整数序列,采用顺序存储结构(下标为0的元素存储n,从下标为1的元素开始依次存储二叉树各结点)建立一棵完全二叉树。
当输入n=0时,表示输入结束。
Output
根据构建的顺序结构的完全二叉树,依次执行前序(递归)遍历操作、中序(非递归)遍历操作和后序(递归)遍历操作,每种遍历操作的结果各占一行,数据之间以空格间隔,最后一个数据之后为换行。
Sample Input
5
3 2 4 1 8
8
78 66 91 -121 57 0 1 6
15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0
Sample Output
3 2 1 8 4
1 2 8 3 4
1 8 2 4 3
78 66 -121 6 57 91 0 1
6 -121 66 57 78 0 91 1
6 -121 57 66 0 1 91 78
1 2 4 8 9 5 10 11 3 6 12 13 7 14 15
8 4 9 2 10 5 11 1 12 6 13 3 14 7 15
8 9 4 10 11 5 2 12 13 6 14 15 7 3 1
代码
#include<iostream>
#include<stack>
using namespace std;
const int MaxBinarySize = 201;
class SeqBinaryTree {
int data[MaxBinarySize];
int size;
public:
SeqBinaryTree(int = 0);
void CreateBianryTree();
void PreOrder(int root = 1);
void InOrder(int root = 1);
void PostOrder(int root = 1);
};
SeqBinaryTree::SeqBinaryTree(int size)
{
this->size = size;
}
void SeqBinaryTree::CreateBianryTree()
{
data[0] = size;
for (int i = 1; i < size; i++)
cin >> data[i];
}
void SeqBinaryTree::PreOrder(int root)
{
if (root >= size) return;
if (root == 1)
cout << data[root];
else cout << ' ' << data[root];
if (2 * root < size)
PreOrder(2 * root);
if (2 * root + 1 < size)
PreOrder(2 * root + 1);
}
void SeqBinaryTree::InOrder(int root)
{
int count = 0;
stack<int>s;
while (!s.empty() || root < size)
{
while (root < size)
{
s.push(root);
root *= 2;
}
if (!s.empty())
{
root = s.top();
s.pop();
if (count == size - 2)
cout << data[root] << endl;
else cout << data[root] << ' ';
count++;
root = root * 2 + 1;
}
}
}
void SeqBinaryTree::PostOrder(int root)
{
if (root >= size) return;
if (2 * root < size)
PostOrder(2 * root);
if (2 * root + 1 < size)
PostOrder(2 * root + 1);
if (root == 1)
cout << data[root] << endl;
else cout << data[root] << ' ';
}
int main()
{
int n;
while (cin >> n)
{
if (n == 0) break;
SeqBinaryTree sbt(n + 1);
sbt.CreateBianryTree();
sbt.PreOrder();
cout << endl;
sbt.InOrder();
sbt.PostOrder();
}
}