当前位置: 首页 > 工具软件 > Leaves > 使用案例 >

浙大数据结构03-树2 List Leaves

阎功
2023-12-01

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.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

结尾无空行

Sample Output:

4 1 5

结尾无空行

#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef struct
{
    int left,right;
}node;
int buildTree(vector<node>&tree)
{
    int n;
    cin>>n;
    int vis[16];
    for(int i=0;i<n;i++)
    {
        char cl,cr;
        cin>>cl>>cr;
        if(cl != '-')
        {
            tree[i].left = cl-'0';
            vis[tree[i].left]=1;
        }
        else
        {
            tree[i].left = -1;
        }
        if(cr != '-')
        {
            tree[i].right = cr-'0';
            vis[tree[i].right]=1;
        }
        else
        {
            tree[i].right = -1;
        }
    }
    for(int i=0;i<n;i++)
    {
        if(!vis[i])
        {
            return i;
        }
    }
    if(n==1)
    {
        return 0;
    }
    return -1;
}
int main()
{
//    system("chcp 65001");
    cin.tie(0);
    cout.tie(0);
//    freopen("C:/Users/zhaochen/Desktop/input.txt", "r", stdin);
    vector<node>tree(16);
    int root=buildTree(tree),flag=0;
    queue<int>q;
    if(root != -1)
        q.push(root);
    while(!q.empty())
    {
        int top=q.front();
        q.pop();
        node t=tree[top];
        if(t.left != -1)
        {
            q.push(t.left);
        }
        if(t.right != -1)
        {
            q.push(t.right);
        }
        if(t.left == -1 && t.right == -1)
        {
            if(flag)
                cout<< " "<< top;
            else
            {
                flag=1;
                cout<< top;
            }
        }
    }
    return 0;
}

 类似资料: