L2-011 玩转二叉树 (25 分)


此题目参考我的上一篇博客:

题目:

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数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
    作者 陈越 单位 浙江大学 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB  
 代码:
#include 
#include 
using namespace std;

int Pre[30],In[30];
typedef struct BinaryTree{
    int key;
    BinaryTree *left;
    BinaryTree *right;
}BinaryTree,*Tree;

//
int FindRootInInoder(int start,int end,int key){
    for(int i=start;i){
        if(In[i]==key)
            return i;
    }
}

//重构二叉树
BinaryTree *getBinaryTree(int pstart,int pend,int istart,int iend){
    //初始化根节点
    BinaryTree *Root = new struct BinaryTree;
    *Root = {Pre[pstart],NULL,NULL};
    //找中序遍历的根节点位置r
    int r = FindRootInInoder(istart,iend,Pre[pstart]);
    int count = r-istart;//左子树节点个数
    if(r!=istart)
        Root->left = getBinaryTree(pstart+1,pstart+count,istart,r-1);
    if(r!=iend)
        Root->right = getBinaryTree(pstart+1+count,pend,r+1,iend);
    return Root;
}

//镜像二叉树
Tree change(Tree root){
    Tree t;
    if(root){
        if(root->left!=NULL||root->right!=NULL){
            t=root->left;
            root->left=root->right;
            root->right=t;
        }
        change(root->left);
        change(root->right);
    }
    return root;
}

//输出层序遍历
void Sequence(Tree root){
    queue t;
    if(root)
        t.push(root);
    while(!t.empty()){
        root=t.front();
        t.pop();
        cout<key;
        if(root->left)
            t.push(root->left);
        if(root->right)
            t.push(root->right);
        if(!t.empty())
            cout<<" ";
    }
}

int main(){
    int n;
    cin>>n;
    for(int i=0;i)
        cin>>In[i];
    for(int i=0;i)
        cin>>Pre[i];
    Tree root = getBinaryTree(0,n-1,0,n-1);//重构二叉树
    change(root);//镜像二叉树
    Sequence(root);//层序输出
    return 0;
}