经过了一个寒假的练习,做题速度终于快起来了,这题花了40分钟就全部做完了,相比于去年有了很大进步,加油,干就完了!,奥利给。
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
思路:前序遍历和中序遍历还原二叉树,然后翻转二叉树,用队列对二叉树进行层次遍历输处。
#include<iostream>
#include<queue>
using namespace std;
typedef struct node {
int val;
struct node* lchild, * rchild;
}leave;
int pre[31], inde[31];
void recover(leave** tree, int pstart ,int pend,int istart,int iend) {
int temp = pre[pstart],id;
if (pstart > pend || istart > iend) {
(*tree) = NULL;
return;
}
(*tree) = new leave;
(*tree)->val = temp;
for (int i = istart; i <= iend; i++) {//寻找根节点
if (temp == inde[i]) {
id = i;
break;
}
}
recover(&((*tree)->lchild), pstart + 1, pstart + id - istart, istart, id - 1);
recover(&((*tree)->rchild), pstart + id - istart + 1, pend, id + 1, iend);
}
void reverse(leave* root) {
leave* temp;
if (root == NULL) {
return;
}
reverse(root->lchild);
reverse(root->rchild);
temp = root->lchild;
root->lchild = root->rchild;
root->rchild = temp;
}
void cexu(leave* root) {
queue<leave*> line;
cout << root->val;
if (root->lchild != NULL)
line.push(root->lchild);
if (root->rchild != NULL)
line.push(root->rchild);
while(!line.empty()) {
leave* tree;
tree = line.front();
line.pop();
cout <<" " <<tree->val;
if (tree->lchild != NULL)
line.push(tree->lchild);
if (tree->rchild != NULL)
line.push(tree->rchild);
}
}
int main() {
int num;
cin >> num;
for (int i = 0; i < num; i++)
cin >> inde[i];
for (int i = 0; i < num; i++)
cin >> pre[i];
leave *root;
recover(&root, 0, num - 1,0,num-1);
reverse(root);
cexu(root);
return 0;
}