以前就思考过这个问题,但是没有深入的想过,这是一种叫二叉树重建的典型题目
如果给出中序和前序,求出后序遍历。
这道题则求的是交换儿子节点的层序遍历。
二叉树的重建应该怎么重建,首先我们知道,先根遍历,最开始的那个一定是根节点,那么,我们可以从先根遍历开始,对于先根遍历的某个节点,寻找他在中根遍历中的位置,这个位置到先根遍历的位置,中间的节点一定是其左儿子节点,而中间节点后面,一定是右儿子节点。、
#include<iostream> #include<string.h> #include<algorithm> #include<stdio.h> #include<queue> using namespace std; const int maxx = 10110; int pre[maxx]; int in[maxx]; int pos; struct node{ int w,l,r; }tree[maxx]; void build(int l,int r,int n) { if (l==r){ tree[n].w=-1;//当前节点为空 return; } int root=pre[pos++]; tree[n].w=root;//当前节点存储的值 tree[n].l=2*n;//这个节点的左儿子节点编号 tree[n].r=2*n+1;//这个节点的右儿子节点编号 int mid=find(in+1,in+r,root)-in;// 得到当前节点在中序遍历数组中的下标 build(l,mid,2*n);//重建左子树 build(mid+1,r,2*n+1);//重建右子树 } void print(){ queue<int>q; q.push(1); int s; while(!q.empty()){ s=q.front(); q.pop(); if (tree[s].w!=-1){ if (s!=1){ printf(" "); } printf("%d",tree[s].w); q.push(tree[s].r); q.push(tree[s].l); } } printf(" "); } int main(){ int n; while(~scanf("%d",&n)){ pos=1; for (int i=1;i<=n;i++){ scanf("%d",&in[i]); } for (int i=1;i<=n;i++){ scanf("%d",&pre[i]); } build(1,n+1,1); print(); } return 0; }