1020 Tree Traversals
作者: CHEN, Yue
單位: 浙江大學
時間限制: 400 ms
內存限制: 64 MB
代碼長度限制: 16 KB
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
題意
給出一棵樹的後序遍歷和中序遍歷結果,讓你根據這兩個序列求出這棵樹的層序遍歷序列…
解答
#include <iostream>
#include<queue>
using namespace std;
struct Node{//樹節點
int data;
Node *lchild, *rchild;
Node(int d) {
data = d; lchild = rchild = NULL;
}
};
int n,post[35],in[35];//分別存放中序和後續序列
int pos[35];
queue<Node*> q;
Node* tran(int a[],int b[],int postl,int postnum,int inl,int innum) {//遞歸求解
if (postnum<=0)return NULL;
int r=pos[postl+postnum-1];
Node *temp = new Node(a[r]);
temp->lchild = tran(a, b, postl, r-inl,inl,r-inl);
temp->rchild = tran(a, b, postl+r-inl,innum-(r-inl)-1,r+1,innum-(r-inl)-1);
return temp;
}
int main(){
cin >> n;
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++) {
cin >> in[i];
for (int j = 0; j < n; j++) {
if (in[i] == post[j])
pos[j] = i;
}
}
Node *root=tran(in,post,0,n,0,n);
q.push(root);bool first=true;
while (!q.empty()) {
if (q.front()->lchild != NULL)
q.push(q.front()->lchild);
if (q.front()->rchild != NULL)
q.push(q.front()->rchild);
if(first){
first=false;
}else
cout<<" ";
cout << q.front()->data;
q.pop();
}
return 0;
}
這個破題花了我好多時間,找了好久才找到問題所在:寫代碼的時候有一個括號的位置寫錯了,導致中間遞歸的時候出現了問題,檢查的時候一直想着這個思路沒有問題,萬萬沒想到是這麼一個小細節上的問題,以後需要引以爲戒!!!切記!!