一、题目描述
假设二叉树用二叉链表存储,用先序序列结果创建。输入二叉树的先序序列,请你先创建二叉树,并对树做个镜面反转,再输出反转后的二叉树的先序遍历、中序遍历、后序遍历和层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。
–程序要求–
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio.h
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
二、输入与输出
1.输入
t组测试数据
每组测试数据是一个二叉树的先序遍历序列,#表示空树
3
41#32###65##7##
AB#C##D##
AB##C##
2.输出
对每棵二叉树,输出镜面反转后的先序、中序、后序和层次遍历序列。如果空树,输出四个NULL(后面不加空格)。如下:
NULL
NULL
NULL
NULL
4 6 7 5 1 3 2
7 6 5 4 3 2 1
7 5 6 2 3 1 4
4 6 1 7 5 3 2
A D B C
D A C B
D C B A
A D B C
A C B
C A B
C B A
A C B
三、参考代码
#include <iostream>
#include <string>
#include<queue>
#include<stack>
using namespace std;
class TreeNode
{
public:
char ch;
TreeNode* lchild;
TreeNode* rchild;
TreeNode* parent;
TreeNode() { lchild = NULL, rchild = NULL; parent = NULL; }
};
class Tree
{
public:
TreeNode* root;
char ch;
Tree() { };
~Tree() {};
void Create()
{
root = CreateTree();
}
TreeNode* CreateTree()//递归建树
{
TreeNode* n;
cin >> ch;
if (ch == '#')
{
n = NULL;
}
else
{
n = new TreeNode();
n->ch = ch;
n->lchild = CreateTree();
if (n->lchild != NULL)
{
n->lchild->parent = n;
}
n->rchild = CreateTree();
if (n->rchild != NULL)
{
n->rchild->parent = n;
}
}
return n;
}
void Trans(TreeNode* t)
{
if (t)
{
Trans(t->lchild);
Trans(t->rchild);
TreeNode* c = t->lchild;
t->lchild = t->rchild;
t->rchild = c;
}
else
{
return;
}
}
void Prepri(TreeNode* t)
{
if (t)
{
cout << t->ch << " ";
Prepri(t->lchild);
Prepri(t->rchild);
}
}
void Minpri(TreeNode* t)
{
if (t)
{
Minpri(t->lchild);
cout << t->ch << " ";
Minpri(t->rchild);
}
}
void Pospri(TreeNode* t)
{
if (t)
{
Pospri(t->lchild);
Pospri(t->rchild);
cout << t->ch<<" ";
}
}
void cengpri(TreeNode* t)
{
queue<TreeNode*>q;
TreeNode* now = t;
if (now)
{
q.push(now);
}
while (!q.empty())
{
now = q.front();
q.pop();
if (now != NULL)
{
cout << now->ch<<" ";
if (now->lchild)
{
q.push(now->lchild);
}
if (now->rchild)
{
q.push(now->rchild);
}
}
}
}
void pri()
{
if (root == NULL)
{
cout << "NULL" << endl;
cout << "NULL" << endl;
cout << "NULL" << endl;
cout << "NULL" << endl;
}
else
{
Trans(root);
this->Prepri(root);
cout << endl;
this->Minpri(root);
cout << endl;
this->Pospri(root);
cout << endl;
this->cengpri(root);
cout << endl;
}
}
};
int main()
{
int sum;
cin >> sum;
while (sum--)
{
Tree t;
t.Create();
t.pri();
}
return 0;
}
/**********************************************************************
Problem: 1069
Language: C++
Result: AC
Time:11 ms
Memory:2236 kb
**********************************************************************/