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

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

二叉树的四种常用遍历方式

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

Tree Traversals

原题链接

PAT甲级 1020 Tree Traversals

题目大意

给出N个结点的二叉树的后序序列和中序序列,输出该二叉树的层序遍历序列。

解题思路

  1. 根据后序序列和中序序列构造出二叉树的结构。如题例,后序序列的最后一个结点是4,是根结点。根据中序序列,4的左半部分是4的左子树,4的右半部分是4的右子树。将左右子树分别看作一个树,在对应后序序列找到最后一个结点(根结点),如此递归,即可实现二叉树的构造。
  2. 对二叉树进行层序遍历输出。使用queue队列结构,首先插入根结点,然后进入一个queue不为空的循环(输出队首结点的值,判断队首结点是否有左右子结点,若有则按顺序入队,弹出队首元素)。

示例代码

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

struct Node{
    
    
    int value;
    Node* left;
    Node* right;
};
int N, postord[30], midord[30];

Node* ConstructTree(int post_head, int post_tail, int mid_head, int mid_tail){
    
    
    if(post_head>post_tail) return NULL;

    //根据后序序列区间和中序序列区间构建二叉树,返回根节点的指针
    Node* root = new Node;
    root->value = postord[post_tail];

    int index;//根节点在中序序列中的位置
    for(index=mid_head; midord[index]!=postord[post_tail]; index++);

    //左子树的节点个数
    int left_len = index-mid_head;

    //左子树
    root->left = ConstructTree(post_head, post_head+left_len-1, mid_head, index-1);
    //右子树
    root->right = ConstructTree(post_head+left_len, post_tail-1, index+1, mid_tail);

    return root;
}


int main(){
    
    
    cin >> N;
    for(int i=0; i<N; i++)  cin >> postord[i];
    for(int i=0; i<N; i++)  cin >> midord[i];

    Node* root = ConstructTree(0, N-1, 0, N-1);

    queue<Node*> que;
    bool isRoot = true;
    que.push(root);
    while(!que.empty()){
    
    
        Node* np = que.front();
        if(!isRoot) cout << " ";
        isRoot = false;
        cout << np->value;

        if(np->left)    que.push(np->left);
        if(np->right)   que.push(np->right);

        que.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/Dae_Lzh/article/details/122843350