1

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 }

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.

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

题目大意:

给定一颗二叉树的先序和中序序列,需要输出该二叉树的左视图,也就是每一层最左边的结点。

算法思路:

先根据先序和中序进行建树,然后使用层次遍历获取每一个结点的根节点,并使用currentLevel记录当前结点所处层次,在结点的层次第一次发生变化的时候就是每一层的最左结点,然后使用result数组进行保存,并更新当前节点所处层次,最后输出即可

提交结果:

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;
}

乔梓鑫
569 声望17 粉丝

主要分享个人学习经验和心得