PAT 1020 Tree Traversals (二叉树的遍历)

1020 Tree Traversals(25 分)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

//题目大意:给出一颗二叉树的后序遍历序列和中序遍历序列,求该二叉树的层序遍历序列

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

const int maxn = 50;
struct node{
  int data;
  node* lchild;
  node* rchild;
};

int in[maxn], post[maxn]; //中序,后序
int n; //节点个数

//当前二叉树的后序序列区间为[postL,postR], 中序序列区间为[inL, inR]
//通过不断递推不断更新区间,create函数返回构建出的二叉树的根节点
node* create(int postL, int postR, int inL, int inR)
{
    if(postL > postR) //后续序列长度小于0时,直接返回
        return NULL;
    node* root = new node; //构建一个新的结点,用来存放当前二叉树的根结点
    root->data = post[postR]; //新结点的数据域为根结点的值
    int k;
    for(k = inL; k <= inR; k++)
    {
        if(post[postR] == in[k]) //在中序序列中找到等于post[postR]的结点,方便判断中序序列中的左子树和右子树
        {
            break;
        }
    }
    int numLeft = k - inL;//左子树结点的个数
    //返回左子树的根节点地址,赋值给root的左指针
    root->lchild = create(postL, postL+numLeft-1, inL, k-1);
    //返回右子树的根节点地址,赋值给root的右指针
    root->rchild = create(postL+numLeft, postR-1, k+1, inR);
    return root;

}

int num = 0; //用来记录已经输出结点的个数
void BFS(node* root)
{
    queue<node*> q; //队列里是储存地址
    q.push(root); //先将根节点地址存入队列,接下来通过队列进行层序遍历
    while(!q.empty())
    {
        node* now = q.front(); //取出首元素
        q.pop();
        if(num != 0)
            printf(" ");
        printf("%d", now->data);
        num++;
        if(now->lchild != NULL) //如果左子树非空,则先将左子树入队列
           q.push(now->lchild);
        if(now->rchild != NULL)//如果右子树非空,再将右子树入队列
           q.push(now->rchild);

    }
}

int main()
{
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &post[i]);
    }
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &in[i]);
    }
    node* root = create(0, n-1, 0, n-1); //建树
    BFS(root); //层序遍历
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42819248/article/details/82633146
今日推荐