当前位置: 代码迷 >> 综合 >> (建树、层次遍历)7-11 玩转二叉树 (25 分)
  详细解决方案

(建树、层次遍历)7-11 玩转二叉树 (25 分)

热度:48   发布时间:2023-11-02 19:07:19.0

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

输入格式:

输入第一行给出一个正整数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<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<set>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std; 
const int maxn=35;typedef struct BiNode{int data;struct BiNode *lchild,*rchild;
}BiNode,*BiTree;void Create(int *s1,int *s2,int num,BiTree &T){if(num==0){T=NULL;return ;	} T=new BiNode;T->data=s2[0];int i;//printf("num=%d,s2[0]=%d\n",num,s2[0]);for(i=0;s1[i]!=s2[0];i++);Create(s1,s2+1,i,T->rchild);Create(s1+1+i,s2+1+i,num-i-1,T->lchild);
}void LevelTraverse(BiTree T){queue<BiTree> q;BiTree p;bool flag=false;if(T){q.push(T);while(!q.empty()){p=q.front();if(flag) printf(" %d",p->data);else{printf("%d",p->data);flag=true;}q.pop();if(p->lchild) q.push(p->lchild);if(p->rchild) q.push(p->rchild);}printf("\n");}
}int main(){int str1[maxn],str2[maxn];int n;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&str1[i]);}for(int i=0;i<n;i ++){scanf("%d",&str2[i]);}BiTree T=NULL;Create(str1,str2,n,T);LevelTraverse(T);return 0;
}

 

  相关解决方案