給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹作個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將全部非葉結點的左右孩子對換。這裏假設鍵值都是互不相等的正整數。node
輸入格式: ios
輸入第一行給出一個正整數N(<=30),是二叉樹中結點的個數。第二行給出其中序遍歷序列。第三行給出其前序遍歷序列。數字間以空格分隔。ide
輸出格式: idea
在一行中輸出該樹反轉後的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多餘空格。spa
輸入樣例:7 1 2 3 4 5 6 7 4 1 3 2 6 5 7輸出樣例:
4 6 1 7 5 3 2.net
勉強敲出來了,包括已知中序和前序建樹求層序遍歷樹的序列,雖然還有兩組數據沒有過,可是也夠了。code
O(∩_∩)O哈哈~blog
#include <iostream> #include <cstring> #include <cstdio> #include <string> #include <queue> #include <algorithm> #include <cstdlib> using namespace std; const int maxn = 35 ; int n, num; string a, b; typedef struct node{ int data ; struct node *lchild, *rchild; }*BiTree, BiNode; void Creat_Tree(BiTree & T, string a, string b){ if( b.length() == 0 ){ T = NULL ; return ; } char root_Node = b[0]; int index = a.find(b[0]); string l_a = a.substr(0,index); string r_a = a.substr(index+1); int l_len = l_a.length(); int r_len = r_a.length(); string l_b = b.substr(1,l_len); string r_b = b.substr(1+l_len); T = (BiTree)malloc(sizeof(BiNode)); if( T!=NULL){ T -> data = root_Node - 48 ; Creat_Tree(T->lchild, l_a, l_b); Creat_Tree(T->rchild, r_a, r_b); } } int main(){ BiTree T; cin >> n ; if( n == 0 ) return 0 ; for(int i=0; i<n; i++){ cin >> num ; a.push_back(num + '0'); } for(int i=0; i<n; i++){ cin >> num ; b.push_back(num+'0'); } Creat_Tree(T,a,b); queue<BiTree> q; q.push(T); bool flag = true ; while( !q.empty() ){ BiTree m = q.front(); if( flag ){ cout << m->data ; flag = false ; } else{ cout << " " << m->data ; } if( m->rchild ) q.push(m->rchild); if( m->lchild ) q.push(m->lchild); q.pop(); } cout << endl ; return 0; }
加個正確的解答吧。完美AC的。ci
來源:http://blog.csdn.net/idealism_xxm/article/details/51584798get
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN=35; int n,cnt,root; int inod[MAXN],preod[MAXN]; int q[35],head,tail; struct Node { int lson,rson,num; }tr[MAXN]; int dfs(int pl,int pr,int il,int ir) { if(pl==pr) { tr[cnt].lson=tr[cnt].rson=-1; tr[cnt].num=preod[pl]; return cnt++; } for(int i=il;i<=ir;++i) { if(preod[pl]==inod[i]) { int cur=cnt++; tr[cur].lson=tr[cur].rson=-1; tr[cur].num=preod[pl]; if(il<i) { tr[cur].lson=dfs(pl+1,pl+i-il,il,i-1); } if(i<ir) { tr[cur].rson=dfs(pl+i-il+1,pr,i+1,ir); } return cur; } } return cnt; } int main() { while(1==scanf("%d",&n)) { for(int i=0;i<n;++i) { scanf("%d",inod+i); } for(int i=0;i<n;++i) { scanf("%d",preod+i); } cnt=0; root=dfs(0,n-1,0,n-1); head=tail=0; if(tr[root].rson!=-1) { q[tail++]=tr[root].rson; } if(tr[root].lson!=-1) { q[tail++]=tr[root].lson; } printf("%d",tr[root].num); while(head!=tail) { printf(" %d",tr[q[head]].num); if(tr[q[head]].rson!=-1) { q[tail++]=tr[q[head]].rson; } if(tr[q[head]].lson!=-1) { q[tail++]=tr[q[head]].lson; } ++head; } printf("\n"); } return 0; }