Description
给定一个用于表示二叉树的一维数组,该数组长度为n。该数组是按照一种类似于层序遍历的方式表示二叉树的,用数字-1表示某个结点为空。
根据给定的一维数组,构建二叉树并依次输出该二叉树的前序、中序、后序遍历。
Input
第一行输入t,表示有t个测试样例。
第二行起,每一行首先输入一个正整数n,接下来依次输入n个整数。
以此类推,共输入t个测试样例。
Output
每三行依次输出每个二叉树的前序、中序、后序遍历。
共输出t个二叉树。
注意输出末尾的空格。
Sample
#0
Input
4 5 1 -1 2 3 4 7 1 2 2 3 4 4 3 7 1 2 2 -1 3 -1 3 7 1 2 -1 3 -1 4 -1
Output
1 2 3 4 1 3 2 4 3 4 2 1 1 2 3 4 2 4 3 3 2 4 1 4 2 3 3 4 2 4 3 2 1 1 2 3 2 3 2 3 1 2 3 3 2 3 2 1 1 2 3 4 4 3 2 1 4 3 2 1
Hint
1 <= 结点个数 <= 1000
1 <= 结点值 <= 100
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
class BiNode
{
public:
int data;
BiNode* lchild;
BiNode* rchild;
BiNode() :lchild(NULL), rchild(NULL) {}
BiNode(int a) :data(a), lchild(NULL), rchild(NULL) {}
~BiNode()
{
delete lchild;
delete rchild;
}
};
class BiTree
{
private:
BiNode* Root;
public:
BiTree() :Root(NULL) {}
~BiTree()
{
delete Root;
}
BiNode* levelCreate(int* a, int n) //伪层序遍历构建二叉树
{
BiNode* p = NULL; //建一个结点作为根节点建树,最后返回这个结点 ,记得初始化
queue<BiNode*> q; //构建存结点的队列
int temp;
int i = 0;
temp = a[i];
i++;
if (temp != -1) //如果数据不为空,则存入树中
{
BiNode* t = new BiNode(temp);
p = t;
q.push(p);
}
while (!q.empty() && i < n)
{
BiNode* root = q.front(); //取出队首,赋给新建的结点root,使它作为根结点,下面围绕它建树
temp = a[i];
if (temp != -1 && i < n)
{
BiNode* m = new BiNode(temp);
root->lchild = m;
q.push(m);
}
i++; //注意一定要在if外加i
temp = a[i];
if (temp != -1 && i < n)
{
BiNode* m = new BiNode(temp);
root->rchild = m;
q.push(m);
}
i++;
q.pop(); //记得最后将队列清空
}
return p;
}
void PreOrder(BiNode* T)//前序
{
if(T)
{
cout << T->data << " ";
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void MidOrder(BiNode* T)//中序
{
if(T)
{
MidOrder(T->lchild);
cout << T->data << " ";
MidOrder(T->rchild);
}
}
void PostOrder(BiNode* T)//后序
{
if(T)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data << " ";
}
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
int n, a;
cin >> n;
int *arry = new int[n];
for (int i = 0; i < n; i++)
{
cin>>arry[i];
}
BiTree tree;
BiNode* r = tree.levelCreate(arry, n);
tree.PreOrder(r);
cout << endl;
tree.MidOrder(r);
cout << endl;
tree.PostOrder(r);
cout << endl;
cout << endl;
}
return 0;
}