团体程序设计天梯赛(L2-006 树的遍历 (25 分))

题目:

 

思路分析:

我们可以根据中序遍历和后序遍历的特点找到那个共同的根 中序在中间位置 后序在最后

那么我们就直接在中序中找那个元素就行 然后把分成俩部分就行建树

按层次输出用queue就行 bfs遍历

代码实现:

const int MAX=110;
struct node{
    node *l,*r;
    int data;
};
int mid[MAX],last[MAX];
int n;
node *creat(int l1,int r1,int l2,int r2){
    if(l1>r1||l2>r2){
        return NULL;
    }
    node *root=new node;
    root->data=last[r2];
    root->l=NULL;
    root->r=NULL;
    int i;
    for(i=l1;i<=r1;i++){
        if(mid[i]==last[r2]){
            break;
        }
    }
    int num=i-l1;
    root->l=creat(l1,i-1,l2,l2+num-1);
    root->r=creat(i+1,r1,l2+num,r2-1);
    return root;
}
void print(node *root){
    queue<node*>qu;
    if(root){
        qu.push(root);
        cout<<qu.front()->data;
    }
    while (!qu.empty()) {
        node *root=qu.front();
        qu.pop();
        if(root->l){
            cout<<" "<<root->l->data;
            qu.push(root->l);
        }
        if(root->r){
            cout<<" "<<root->r->data;
            qu.push(root->r);
        }
    }
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>last[i];
    }
    for(int i=0;i<n;i++){
        cin>>mid[i];
    }
    node *root=NULL;
    root=creat(0,n-1,0,n-1);
    print(root);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭晋龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值