1020 Tree Traversals (25分)

Posted tomori

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1020 Tree Traversals (25分)相关的知识,希望对你有一定的参考价值。

题干

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

解释

意思就是给你一个二叉树的后序遍历和中序遍历结果,让你求它的层序遍历结果

思路

用所给的两个序列把树还原出来,然后bfs,就好了。

问题的关键在于怎么还原这个树,通过查看后序遍历来得到根,然后通过根在中序遍历中的位置,得到这个根的左子树部分和右子树部分,问题是递归的,所以用dfs做。

#include<iostream>
#include<vector>
#include<queue> 

using namespace std;

const int N = 100;
int a[N];
int n;
int lc[N], rc[N];
int in[N], post[N];
vector<int> ans;

int dfs(int i, int j, int l, int r){// 后序遍历序列中的l~r,对应中序遍历中的i~j这一批结点
    if(i > j) return 0;
    int x = post[j], idx = a[x];
    int d = idx - l;
    
    lc[x] = dfs(i, i + d - 1, l, idx - 1);
    rc[x] = dfs(i + d, j - 1, idx + 1, r - 1);
    
    return x;
}

void bfs(int x){
	queue<int> q;
	q.push(x);
	
	while(q.size()){
		int t = q.front();
		q.pop();
		ans.push_back(t);
		
		if(lc[t]) q.push(lc[t]);
		if(rc[t]) q.push(rc[t]); 
	}
}

int main(){
    cin >> n;
    
    for(int i = 0; i < n; i ++) cin >> post[i];
    for(int i = 0; i < n; i ++) cin >> in[i], a[in[i]] = i;
    
    int x = dfs(0, n - 1, 0, n - 1);

    bfs(x);
    
    for(int i = 0; i < n; i ++) cout << ans[i] << (i == n - 1 ? "" : " ");
    return 0;
}

还有这题有个谜之测试点是什么鬼啊。。。不是说N <= 30吗








以上是关于1020 Tree Traversals (25分)的主要内容,如果未能解决你的问题,请参考以下文章

1020 Tree Traversals (25 分)

1020 Tree Traversals (25分)

1020 Tree Traversals (25 分)

PAT Advanced 1020 Tree Traversals (25分)

1020 Tree Traversals (25 分) 难度: 中 / 知识点: 哈希表建树 遍历树

PAT 1020 Tree Traversals