1020 Tree Traversals (25 分)(树的遍历)

本文详细解析了一道关于二叉树遍历的问题,重点在于如何根据后序和中序遍历序列,输出对应的层序遍历序列。通过深入分析递归算法和关键点,帮助读者理解树遍历的复杂过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

本题考查的是树的遍历,此处扩展了博客[^1]的解法,将博客的例子中序列的起点和终点分开透彻地阐述了,但是题主在做本题时仍然还是花了一些时间做调试工作,说明对此类题目理解得还不够透彻,因此仍继续追加记录以做理解。

注意点1:本题在计算左右子树起点和终点的时,器依靠子树的长度做相对i的偏移进行计算的,不能简单的认为中序和后序处于对齐状态,这个思考是错误的,但是往往做题出现迷糊的时容易产生两序列对齐的错觉,从而没有依据长度偏移计算点的索引。透彻地说,我们计算的时候有五个锚点,函数提供的左右子树的起点终点四个锚点和中序中找出的根节点一个锚点,然后计算新的左右子树的起点和终点是依据五个锚点和子树长度(做偏移)求解的。

注意点2:递归终止的条件是当起点跑到终点的后面,这是不合理的,以此作为递归终止点;另外在中序中找寻根节点时,i的搜索范围是i<inright,不能涵盖等号,这个还未找到合理的解释,后续再做领悟。

#include <iostream> 
#include <vector> 
using namespace std;
vector<int> post,in;
vector<int> a[30];
FILE *f;
void getpre(int postleft,int postright,int inleft,int inright,int height){
    if(postleft>postright || inleft>inright) return ;
    int i=inleft;
    while(i<inright && post[postright]!=in[i]) i++;
//  cout<<post[postright];
    a[height].push_back(post[postright]);
    getpre(postleft,postleft+i-inleft-1,inleft,i-1,height+1);
    getpre(postleft+i-inleft,postright-1,i+1,inright,height+1);
}
int main(){
    int n;
    cin>>n;
    in.resize(n),post.resize(n);
    for(int i=0;i<n;i++) cin>>post[i];
    for(int i=0;i<n;i++) cin>>in[i];
    getpre(0,n-1,0,n-1,0);
    bool first=true;
    for(int i=0;i<30;i++){
        for(int j=0;j<a[i].size();j++){
            if(first){
                cout<<a[i][j];
                first=false;
            }else cout<<" "<<a[i][j];
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值