ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

03-树2 List Leaves (25 分)

2021-03-19 12:33:31  阅读:204  来源: 互联网

标签:03 right tree Leaves List queue front visited left


03-树2 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.

Sample Input:

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

Sample Output:

4 1 5

代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef struct node Node;
struct node {
    int left, right;
};
int judge(char c) {
    if (c >= '0' && c <= '9') return (int)(c - '0');
    else return -1;
}
void BFS(Node *tree, bool *visited, int N, int root) {
    int queue[100], front = 0, rear = 0;
    bool first = true;
    queue[rear++] = root, visited[root] = true;
    while (front != rear) {
        if (tree[queue[front]].left == tree[queue[front]].right) {
            if (first) printf("%d", queue[front]), first = false;
            else printf(" %d", queue[front]);
        }
        if (tree[queue[front]].left != -1)
            queue[rear++] = tree[queue[front]].left, visited[rear - 1] = true;
        if (tree[queue[front]].right != -1)
            queue[rear++] = tree[queue[front]].right, visited[rear - 1] = true;
        front++;
    }
}
int main() {
    int N;
    cin >> N;
    getchar();
    Node tree[10];
    bool *visited = (bool*)malloc(sizeof(bool) * N);
    for (int i = 0; i < N; i++) {
        char a, b;
        scanf("%c %c", &a, &b);
        getchar();
        tree[i].left = judge(a), tree[i].right = judge(b);
        if (tree[i].left != -1) visited[tree[i].left] = true;
        if (tree[i].right != -1) visited[tree[i].right] = true;
    }
    int root = 0;
    while(visited[root]) root++;
    for(int i = 0; i < N; i++) visited[i] = 0;
    BFS(tree, visited, N, root);
    return 0;
}

标签:03,right,tree,Leaves,List,queue,front,visited,left
来源: https://blog.csdn.net/mistymountain32/article/details/115003448

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有