zoukankan      html  css  js  c++  java
  • 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吗

  • 相关阅读:
    迁移式学习
    VMware Workstation 16激活码
    OpenStack安装部署
    git码云操作
    vs 2019 正则替换
    linux中Redis单机安装
    ASP.NET/C#执行数据库过程函数带RETURN的项目接收。
    IDEA配置部属Tomcat
    Java集合之HashMap源码分析(put()方法)
    反编译一款APP然后重新打包(Windows环境)
  • 原文地址:https://www.cnblogs.com/tomori/p/13399381.html
Copyright © 2011-2022 走看看