PAT003 List Leaves

题目:

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

分析: 主要有两步,一是根据输入数据创建树,二是对树进行层序遍历。其中用到了通过链表创建的队列。代码(c):
#include <stdio.h>
typedef struct listNode {

    int value;
    char leftIndex, rightIndex;
    struct listNode *left;
    struct listNode *right;
    struct listNode *next; // 队列用

} ListNode;

typedef struct queue {

    ListNode *front;
    ListNode *rear;

} Queue;
Queue *createQueue()
{
    Queue *queue = (Queue *)malloc(sizeof(Queue));
    queue->front = NULL;
    queue->rear = NULL;
    return queue;
}

void addToQueue(Queue *queue, ListNode *node)
{
    if (!(queue->rear)) {
        queue->rear = node;
    } else {
        queue->rear->next = node;
        queue->rear = node;
    }

    if (!(queue->front)) {
        queue->front = node;
    }
}

ListNode *deleteFromQueue(Queue *queue)
{
    ListNode *temp = queue->front;
    if (temp) {
        queue->front = queue->front->next;
        return temp;
    } else {
        return NULL;
    }
}

int isEmptyQueue(Queue *queue)
{
    if (queue->front == NULL) {
        return 1;
    } else {
        return 0;
    }
}

// List Leaves
int main()
{
    // 接受输入
    int nodeCount;
    scanf("%d", &nodeCount);

    ListNode a[nodeCount];
    int sum = 0;
    for (int i = 0; i < nodeCount; i++) {
        char leftIndex, rightIndex;
        getchar(); // 去除多余的 ‘\n‘
        scanf("%c %c", &leftIndex, &rightIndex);
        ListNode input = *(ListNode *)malloc(sizeof(ListNode));
        input.leftIndex = leftIndex;
        input.rightIndex = rightIndex;
        input.left = NULL;
        input.right = NULL;
        input.value = i;
        a[i] = input;
        sum += (leftIndex == ‘-‘ ? 0 : leftIndex - ‘0‘) + (rightIndex == ‘-‘ ? 0 : rightIndex - ‘0‘);
    }

    // 建树
    for (int i = 0; i < nodeCount; i++) {
        ListNode *node = &(a[i]);
        char leftIndex = node->leftIndex;
        char rightIndex = node->rightIndex;
        node->left = leftIndex != ‘-‘ ? &(a[leftIndex - ‘0‘]) : NULL;
        node->right = rightIndex != ‘-‘ ? &(a[rightIndex - ‘0‘]) : NULL;
    }
    // 根节点下标
    int rootIndex = (nodeCount - 1) * nodeCount / 2 - sum;
    ListNode *root = &a[rootIndex];

    // 层次遍历 遇到叶节点输出
    Queue *queue = createQueue();
    addToQueue(queue, root);
    int flag = 1;
    while (!isEmptyQueue(queue)) {
        ListNode *node = deleteFromQueue(queue);
        if (!(node->left) && !(node->right)) {
            if (flag) {
                printf("%d", node->value);
                flag = 0;
            } else {
                printf(" %d", node->value);
            }
        }
        if (node->left) {
            addToQueue(queue, node->left);
        }
        if (node->right) {
            addToQueue(queue, node->right);
        }
    }
}

运行结果:

时间: 2024-09-29 17:39:07

PAT003 List Leaves的相关文章

【数据结构】The Falling Leaves(6-10)

[UVA699]The Falling Leaves 算法入门经典第6章例题6-10(P159) 题目大意:有一颗二叉树,求水平位置的和. 试题分析:乱搞就可以过,将树根节点的pos记为0,向左-1,向右+1,统计答案即可. #include<iostream> #include<cstring> #include<cstdio> #include<vector> #include<queue> #include<stack> #in

[LeetCode] Sum of Left Leaves

Find the sum of all left leaves in a given binary tree. Example: 3 / 9 20 / 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 题目要求树的所有左叶节点的和,根据题意判断出所有左叶节点,使用递归即可. class Solution { public: int sumOfLeftLe

Find Leaves of Binary Tree 找二叉树的叶节点

Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty. Example:Given binary tree 1 / \ 2 3 / \ 4 5 Returns [4, 5, 3], [2], [1]. Explanation:1. Remove the leaves [4, 5, 3] from the tr

pat1004. Counting Leaves (30)

1004. Counting Leaves (30) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child. Input Each input file contains one

UVa 699.The Falling Leaves【7月23】

The Falling Leaves Each year, fall in the North Central region is accompanied by the brilliant colors of the leaves on the trees, followed quickly by the falling leaves accumulating under the trees. If the same thing happened to binary trees, how lar

leetcode-404. Sum of Left Leaves

404. Sum of Left Leaves Find the sum of all left leaves in a given binary tree. Example: 3 / 9 20 / 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.求所有的左叶子节点的和java代码: /** * Definition for a binary tree

UVA 699 The Falling Leaves

#include<cstdio> #include<iostream> #include<queue> #include<cstring> #include<string> #include<math.h> #include<stack> #include<cstdlib> #include<map> #include<algorithm> #include<cctype>

PAT03-树1. 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

POJ 1577 Falling Leaves 二叉树题解

给出按最底层叶子节点到根节点的数据,然后要求重建树,前序输出最终建的树. 都是两个基本操作解决: 1 二叉树插入操作 2 前序遍历 简单题目了. #include <stdio.h> #include <string> #include <algorithm> #include <vector> using std::vector; using std::string; const int MAX_B = 1024; char buf[MAX_B]; int