PTA Data Structures and Algorithms 7-4 List Leaves

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abc15766228491/article/details/86233765

本题为陈越老师、何钦铭老师的数据结构课程的作业
7-4 List Leaves (25 分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.
Output Specification:

For each test case, print in one line all the leaves’ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

题目大意:给出一颗二叉树,要求从上到下从左到右输出叶子节点

二叉树的叶子节点使用结构体进行存储,树的所有节点的结构体放在一个vector里。树的叶子节点结构体有三个元素,分别是左儿子节点在vector里的下标,右儿子在vector里的下标,和当前节点在vector里的下标,这样就可以通过下标访问到整颗树了。

树的层次遍历使用队列,树的根节点先入队列,然后从队列头拿出一个元素,把这个元素的左右儿子从队列尾插入队列,可以达到层次遍历效果。如果一个节点左右儿子都为-1则输出这个节点

#include <iostream>
#include <set>
#include <vector>
#include <queue>
using namespace std;
struct point{
    int left;
    int right;
    int index;
    point(int _left, int _right, int _index):left(_left), right(_right), index(_index){}
};
typedef vector<point> Tree;
set<int> check;
void createTree(Tree &tree, int num, int &root){
    check.clear();
    char temp_cl, temp_cr;
    for (int i = 0; i < num; ++i) {
        cin>>temp_cl>>temp_cr;  
        //  左右儿子的下标
        int cl = temp_cl == '-'? -1: temp_cl-'0';
        int cr = temp_cr == '-'? -1: temp_cr-'0';
        tree.push_back(point(cl, cr, i));
        check.insert(cl);
        check.insert(cr);
    }
    //  找到树根
    int temp_root=0;
    auto item = ++check.begin();
    for(;item!=check.end();item++)
    {
        if(temp_root!=*item) break;
        else temp_root++;
    }
    root = temp_root;
}
void get_result(Tree &tree, int root){
    queue<point> q_p;
    q_p.push(tree[root]);
    int flag = 1;
    //  树的层次遍历
    while(!q_p.empty()){
        point t = q_p.front();
        q_p.pop();
        if(t.right == -1 and t.left == -1)
        {
            if(flag) {
                cout<<t.index;
                flag = 0;
            }
            else{
                cout<<" "<<t.index;
            }
        }
        else{
            if(t.left != -1)
                q_p.push(tree[t.left]);
            if(t.right != -1)
                q_p.push(tree[t.right]);
        }
    }
};

int main()
{
    int num, root;
    cin>>num;
    Tree tree;
    createTree(tree, num, root);
    get_result(tree, root);
}


猜你喜欢

转载自blog.csdn.net/abc15766228491/article/details/86233765