码迷,mamicode.com
首页 > 其他好文 > 详细

1020 Tree Traversals (25分)

时间:2020-07-29 21:34:20      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:print   seq   int   c++   思路   pos   就是   ecif   问题   

题干

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分)

标签:print   seq   int   c++   思路   pos   就是   ecif   问题   

原文地址:https://www.cnblogs.com/tomori/p/13399381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!