【数据结构与算法】玩转二叉树

在这里插入图片描述

输入样例:

7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

输出样例:

4 6 1 7 5 3 2

思路

本题考察由前序中序获得完整二叉树并获得层序遍历
结果,其实并不是很难。
关键点有两个:

  • 由前序中序建立二叉树(用链式结构存储较简单)
  • 将建立的二叉树层序遍历,层序遍历时要逆序输出(可以考虑使用队列或栈)
#include<bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int i=a;i<b;i++)
struct node
{
    int value;
    node* l=NULL,*r=NULL;
};
node* BuildTree(int root,int l,int r,int pre[],int in[],int n)
{
    if(l>r)return NULL;
    node* newroot=new(node);
    newroot->value=pre[root];
    int i=l;
    for(;i<n&&in[i]!=pre[root];i++);
    newroot->l=BuildTree(root+1,l,i-1,pre,in,n);
    newroot->r=BuildTree(root+i-l+1,i+1,r,pre,in,n);
    return newroot;
}
// void travel(node* root)
// {
//     if(root==NULL)return;
//     travel(root->l);
//     cout<<root->value<<" ";
//     travel(root->r);
// }
void BFS(node* root)
{
    int cnt=0;
    if(root==NULL)return;
    queue<node*>q;
    q.push(root);
    while(!q.empty())
    {   
        auto tmp=q.front();
        if(cnt==0)
            cout<<tmp->value;
        else cout<<" "<<tmp->value;
        q.pop();
        if(tmp->r)
        {
            q.push(tmp->r);
        }
        if(tmp->l)
        {
            q.push(tmp->l);
        }
        cnt++;
    }
}
int main()
{
    int n;
    cin>>n;
    int in[n],pre[n];
    For(i,0,n)
        cin>>in[i];
    For(i,0,n)
        cin>>pre[i];
    node* root=BuildTree(0,0,n-1,pre,in,n);
    BFS(root);
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值