PAT(甲級)2020年秋季考試 7-3 Left-View of Binary Tree

7-3 Left-View of Binary Tree (25分)

The left-view of a binary tree is a list of nodes obtained by looking at the tree from left hand side and from top down. For example, given a tree shown by the figure, its left-view is { 1, 2, 3, 4, 5 }node

fig.JPG

Given the inorder and preorder traversal sequences of a binary tree, you are supposed to output its left-view.算法

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20), which is the total number of nodes in the tree. Then given in the following 2 lines are the inorder and preorder traversal sequences of the tree, respectively. All the keys in the tree are distinct positive integers in the range of int.數組

Output Specification:

For each case, print in a line the left-view of the tree. All the numbers in a line are separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.ide

Sample Input:

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

Sample Output:

1 2 3 4 5

題目限制:

image.png

題目大意:

給定一顆二叉樹的先序和中序序列,須要輸出該二叉樹的左視圖,也就是每一層最左邊的結點。spa

算法思路:

先根據先序和中序進行建樹,而後使用層次遍歷獲取每個結點的根節點,並使用currentLevel記錄當前結點所處層次,在結點的層次第一次發生變化的時候就是每一層的最左結點,而後使用result數組進行保存,並更新當前節點所處層次,最後輸出便可code

提交結果:

image.png

AC代碼:

#include<cstdio>
#include<queue>
#include<unordered_map>

using namespace std;

struct Node{
    int data;
    Node* left;
    Node* right;
    int level;
};

int N;//節點個數
int pre[30],in[30];
unordered_map<int,int> pos;//每個節點在中序序列中的個數

Node* createTree(int preL,int preR,int inL,int inR){
    if(preL>preR) return nullptr;
    Node* root = new Node;
    root->data = pre[preL];
    int k = pos[root->data];// 根節點在中序中的位置
    int numOfLeft = k-inL;
    root->left = createTree(preL+1,preL+numOfLeft,inL,k-1);
    root->right = createTree(preL+numOfLeft+1,preR,k+1,inR);
    return root;
}

int currentLevel = 0;
vector<int> result;
void BFS(Node* root){
    root->level = 1;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()){
        Node* t = q.front();
        q.pop();
        if(currentLevel!=t->level){
            // 到達節點層次轉折處
            result.push_back(t->data);
            currentLevel = t->level;
        }
        if(t->left){
            t->left->level = t->level+1;
            q.push(t->left);
        }
        if(t->right){
            t->right->level = t->level+1;
            q.push(t->right);
        }
    }
}

int main(){
    scanf("%d",&N);
    for (int i = 0; i < N; ++i) {
        scanf("%d",&in[i]);
        pos[in[i]] = i;
    }
    for(int i=0;i<N;++i){
        scanf("%d",&pre[i]);
    }
    Node* root = createTree(0,N-1,0,N-1);
    BFS(root);
    for(int i=0;i<result.size();++i){
        printf("%d",result[i]);
        if(i<result.size()-1) printf(" ");
    }
    return 0;
}
相關文章
相關標籤/搜索