题目描述
按顺序方式存储的一棵完全二叉树的结点记录,结点个数为n。根据所输入的顺序结构的结点记录建立二叉树,输出树的先序,中序和后序遍历结果。
注:数字“0”表示不存在此结点,没有孩子结点。
输入
树结点个数n
顺序方式存储的完全二叉树
输出
先序遍历输出
中序遍历输出
后序遍历输出
样例输入
10
1 2 0 3 4 0 0 5 6 7
样例输出
1 2 3 5 6 4 7
5 3 6 2 7 4 1
5 6 3 7 4 2 1
提示
数字“0”的孩子结点全部为“0”
这是非常典型的树的遍历,运用的是递归的思想
(关于树的一些基础知识,大家应该右一定的了解)
先序:根左右
中序:左根右
后序:左右根
我们可以理解为这三种方式的遍历根根节点的遍历顺序有关
(大家应该明白三种遍历方式的流程,这里就不讲解了)
#include <iostream>
using namespace std;
class Tree {
public:
int* data;
int lchild = 0;//左孩子
int rchild = 0;//右孩子
int maxSize;
Tree() {}
Tree(int* elem, int n) {
maxSize = n;
data = new int[maxSize];
for (int i = 0; i < n; i++)
data[i] = elem[i];
}
~Tree() {
delete []data;
}
void PreOrder(int root = 0) {//前序遍历,三种遍历方式其实就是根节点的顺序不同
if(data[root]!=0)//根节点
cout << data[root] << " ";
lchild = root * 2 + 1;//左孩子
if (lchild < maxSize)
PreOrder(lchild);
rchild = root * 2 + 2;//右孩子
if (rchild < maxSize)
PreOrder(rchild);
}
void MedOrder(int root = 0) {//中序遍历
lchild = root * 2 + 1;//左孩子
if (lchild < maxSize)
MedOrder(lchild);
if (data[root] != 0)//根节点
cout << data[root] << " ";
rchild = root * 2 + 2;//右孩子
if (rchild < maxSize)
MedOrder(rchild);
}
void PosOrder(int root = 0) {//后序遍历
lchild = root * 2 + 1;
if (lchild< maxSize)//左孩子
PosOrder(lchild);
rchild = root * 2 + 2;
if (rchild < maxSize)//右孩子
PosOrder(rchild);
if (data[root] != 0)//根节点
cout << data[root] << " ";
}
};
int main() {
int n;
cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
Tree tree(arr, n);
tree.PreOrder();
cout << endl;
tree.MedOrder();
cout << endl;
tree.PosOrder();
cout << endl;
return 0;
}
有问题,欢迎交流