天梯赛 二叉树相关题目

L2 006 树的遍历

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

利用二叉树左右儿子和根节点的下标关系搞

重构树比较直观一点

#include <iostream>
#include <queue>
#include <map>
#include <cmath>
#include <set>
#include <iomanip>
#include <unordered_set>
#include <cstring>
#include <unordered_map>
#include <algorithm>
using namespace std;

const int maxn=35;
int a[maxn];
int b[maxn];
int n;
map<int,int>lis;
// l1 r1记录中序  l2 r2记录后序
void dfs(int num,int l1,int r1,int l2,int r2)
{
    if(l1>r1||l2>r2)return;//越界

    lis[num]=a[r2];//后序遍历的最后一个点一定为根节点

    int j;//记录当前根节点
    for(int i=1;i<=n;i++)//在中序遍历中找当前根节点
    {
        if(b[i]==a[r2])//j左边为左子树 右边为右子树(在中序遍历中)
        {
            j=i;
            break;
        }
    }
    int lnum=j-l1;

    dfs(num*2,l1,j-1,  l2,     l2+lnum-1);
    dfs(num*2+1,j+1,r1,l2+lnum,r2-1      );
}



int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];//后序
    for(int i=1;i<=n;i++)cin>>b[i];//中序
    dfs(1,1,n,1,n);
    int fir=1;
    for(auto x:lis)
    {
        if(fir==1)fir=0;
        else cout<<' ';
        cout<<x.second;
    }cout<<endl;

    return 0;
}

 

 

L2 011玩转二叉树

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

 

n很小的时候就把树给重构出来。。很暴力很直观

层序遍历镜像输出就倒序遍历这一层就行

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
int a[maxn],b[maxn];
map<int,int>tree;
void dfs(int num,int l1,int r1,int l2,int r2)
{
    if(l1>r1||l2>r2)return;
    tree[num]=b[l2];
    int j;
    for(int i=l1;i<=r1;i++)
    {
        if(a[i]==b[l2])//在中序中找到当前根节点
        {
            j=i;
            break;
        }
    }
    int l_num=j-l1;//左子树

    dfs(num*2,  l1, j-1,l2+1,l2+l_num);
    dfs(num*2+1,j+1,r1 ,l2+l_num+1,r2 );

}

int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];//中序
    for(int i=1;i<=n;i++)cin>>b[i];//前序
    dfs(1,1,n,1,n);

    //for(auto x:tree)cout<<' '<<x.second;
    //cout<<endl;
    cout<<tree[1];
    int now=2;
    while(now<10000)
    {
        for(int i=now*2-1;i>=now;i--)
        {
            if(tree.find(i)!=tree.end())
            {
                cout<<' '<<tree[i];
            }
        }
        now=now*2;
    }cout<<endl;


    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值