1110 Complete Binary Tree (25point(s)) - C語言 PAT 甲級

1110 Complete Binary Tree (25point(s))

Given a tree, you are supposed to tell if it is a complete binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) 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 case, print in one line YES and the index of the last node if the tree is a complete binary tree, or NO and the index of the root if not. There must be exactly one space separating the word and the number.

Sample Input:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
Sample Output:

YES 8

Sample Input:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output:

NO 1

題目大意:

輸入 N 個節點,依次給出 N 個節點的左右孩子

輸出判斷是否是完全二叉樹,和最後一個節點號

設計思路:

完全二叉樹,最大的下標值一定等於最大的節點數

  • 用數組存儲二叉樹
  • 利用父節點的左右孩子 2 倍和 2 倍加 1,遞歸出最大的下標值
編譯器:C (gcc)
#include <stdio.h>
#include <stdlib.h>

int tree[20][2];
int imax = 0, ilast = 0;
void dfs(int root, int index)
{
        if (imax < index) {
                imax = index;
                ilast = root;
        }
        if (tree[root][0] != -1)
                dfs(tree[root][0], index * 2);
        if (tree[root][1] != -1)
                dfs(tree[root][1], index * 2 + 1);
}
int main(void)
{
        int n;
        int i, root = 0, child[20] = {0};
        char a[3], b[3];

        scanf("%d", &n);
        for (i = 0; i < n; i++) {
                scanf("%s %s", a, b);
                if (a[0] != '-') {
                        tree[i][0] = atoi(a);
                        child[atoi(a)] = 1;
                } else {
                        tree[i][0] = -1;
                }
                if (b[0] != '-') {
                        tree[i][1] = atoi(b);
                        child[atoi(b)] = 1;
                } else {
                        tree[i][1] = -1;
                }
        }
        while (child[root] == 1)
                root++;
        dfs(root, 1);
        if (imax == n)
                printf("%s %d", "YES", ilast);
        else
                printf("%s %d", "NO", root);

        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章