根据中序后序遍历输出层序遍历

本文介绍了一种通过后序遍历和中序遍历构建二叉树的方法,并实现了层序遍历输出构建后的二叉树。首先,从后序遍历中找到根节点,再从中序遍历中定位该根节点,以此划分左右子树,递归建立整棵树。最后采用队列实现层序遍历。

解题思路:

不管是左右子树还是整棵树,后序遍历的最后一个元素就是根节点,然后从中序遍历中找到根节点在中序遍历的位置,并且记录左子树元素的个数。

中序遍历中根节点以前的位左子树,以后的位右子树,然后递归遍建立左右子树,如果子树为空则返回0,l>r的情况就是子树为空的情况。在根据根节点输出层序遍历就可以了。

#include<iostream>  
#include<cstdio>  
#include<cstring>  
#include<queue>  
using namespace std;  
#define N 35  
int last[N],in[N];  
struct node{  
    int left;  
    int right;  
}tree[N];  
int n,cnt;  
int build(int l1,int r1,int l2,int r2){  
    int root;  
    if(l1 <= r1&&l2 <= r2){  
        root = last[r2];  
        int cnt  = 0;  
        int index;  
        for(index = l1;in[index] != root;index++,cnt++);//判定根节点下标和确定左子树的元素个数   
        tree[root].left = build(l1,index-1,l2,l2+cnt-1);//建立左子树   
        tree[root].right = build(index+1,r1,l2+cnt,r2-1);//建立右子树   
    }else{  
        return 0;  
    }  
    return root;  
}  
void print(int root){  
    queue<int>q;  
    q.push(root);//根节点入队   
    while(!q.empty()){  
        int temp = q.front();  
        cnt++;  
        printf("%d",temp);//输出结点   
        if(cnt != n){  
            printf(" ");  
        }else{  
            printf("\n");  
        }  
        q.pop();  
        if(tree[temp].left){  
            q.push(tree[temp].left);//左子树如队列   
        }  
        if(tree[temp].right){  
            q.push(tree[temp].right);//右子树入队列   
        }  
    }  
}  
int main(){  
//  freopen("input.txt","r",stdin);  
    scanf("%d",&n);  
    for(int i = 1;i <= n;i++){  
        scanf("%d",&last[i]);  
    }  
    for(int i = 1;i <= n;i++){  
        scanf("%d",&in[i]);  
    }  
    int root = build(1,n,1,n);  
    print(root);  
    return 0;  
}   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值