L2-6 树的遍历(递归+bfs)

Posted fatcatm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了L2-6 树的遍历(递归+bfs)相关的知识,希望对你有一定的参考价值。

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

4 1 6 3 5 7 2

解题思路:用递归建立树,然后用bfs遍历即可。重点在于中序序列和后序序列之间子树节点数的关系(15行)

#include<cstdio>
#include<queue>
using namespace std;

typedef struct{
    int lc, rc;
}Tree;
int a[40], b[40];
Tree tr[40]; 

int build(int al, int ar, int bl, int br) {//a为中序序列,b为后序序列 
    if(al > ar) return -1; //边界条件 
    int root = b[br], p1 = al, p2;
    while(a[p1] != root) p1++;
    p2 = p1 - al; //确定后序中左子树节点个数 
    tr[root].lc = build(al, p1 - 1, bl, bl + p2 - 1);
    tr[root].rc = build(p1 + 1, ar, bl + p2, br - 1);
    return root; //返回根节点在后序中的位置 
} 
int main(void)
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &b[i]);
    }
    for(int i = 0; i < n; i++){
        scanf("%d", &a[i]);
    }
    build(0, n - 1, 0, n - 1);
    
    queue<int> q;
    int count = 0;
    q.push(b[n - 1]);
    while(!q.empty()){
        int t = q.front();
        q.pop();
        if(tr[t].lc != -1) q.push(tr[t].lc);
        if(tr[t].rc != -1) q.push(tr[t].rc);
        printf("%d%c", t, ++count == n? \n :  );
    }  
    
    return 0;
} 

 

 

以上是关于L2-6 树的遍历(递归+bfs)的主要内容,如果未能解决你的问题,请参考以下文章

图的遍历方法——DFS和BFS

二叉树遍历(先序,中序,后序,层序)递归和非递归形式

二叉树小结

二叉树小结

二叉树小结

二叉树的深度之DFSBFS