PAT A 1151(甲级 2018年9月真题第四题)

版权声明:欢迎评论和转载,转载时请注明作者和出处,共同维护良好的版权和知识产权秩序。 https://blog.csdn.net/CrazyOnes/article/details/82596927

1151 LCA in a Binary Tree(30 分)

作者: CHEN, Yue

单位: 浙江大学

时间限制: 1000 ms

内存限制: 64 MB

代码长度限制: 16 KB

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

Given any two nodes in a binary tree, you are supposed to find their LCA.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:

For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the binary tree, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

Sample Input:

6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

今年9月份我参加了PAT甲级考试,也就是在前天,这道题在我看来非常有希望全部的case都AC掉,但是很遗憾,没有拿满这30分。

在 PAT个人心得 这篇文章中我也着重的提到了这道题目,这道题连带第二三题都属于比较简单的,但是考试这种东西就是这样,不仅是你会不会做的问题,这是一场限时的竞赛,不仅仅是你能不能写出来的问题,还有你有没有时间写的问题。

这道题开始我的想法就是构建一个树之后再让他转换为静态树(虽然后来我也思考到可以直接构建静态树,不用构建完链表树之后再去转换静态树,但是因为我当时没有试过直接通过前中序遍历构建静态树,所以没有大胆尝试,走了一个感觉稳一点的路线),这时只要获取到两个数字在静态树中的下标值,然后让下标较大的一方不断除以2 ,直到两者的下标相等,就可以找到他们的LCA,即使其中一个节点是另一个节点的祖先的这种情况也是适用的。

如果N的范围特别小,在30及30以内的时候,就可以安心使用静态树了,为什么这么说呢?这正是我一开始没有考虑到的点,就是如果是静态树的话,而给出的树偏偏又是所有的节点只有左子树的那种极端情况,那么第一个节点的下标是2^{0},第二个节点的下标是2^{1},第N个节点的下标就是2^{N - 1},当N大于31的时候就是无法承受的了,并且N的取值范围是 <= 10000,这更加无法使用静态树。

所以唯一的方法就是使用链表树了,其实链表树也不难,使用DFS的方法去找到目标值,如果找到目标值函数返回目标值,如果没有找到目标值,返回-1,然后当两个目标值第一次汇合的时候就是他们的LCA了。这样其实就是在DFS回溯的过程中,不断的比较根节点和左右子树返回的值是不是包含两个目标值,如果包含就输出,不包含就接着将目标值返回。

但是也要注意一种特殊情况:目标值相等的时候,这时候是找不到第二个目标值的,也就是当第一次找到目标值的时候就将其输出就可以了,并且以ancestor的那种形式输出,具体的细节大家可以从代码中去感受。

如果你有更好的代码,也可以贴出来和我交流。


AC代码:

#include <cstdio>

const int maxn = 10010;

struct Tree {
    int key;
    Tree * lchild, * rchild;
};

int n, m, a, b;
//   pre存储先序遍历 in存储中序遍历
int pre[maxn], in[maxn];

Tree* createTree(int, int, int, int);
int dfs(Tree *& root);

int main() {
    // 获取 m n值
    scanf("%d%d", &m, &n);
    for(int i = 0; i < n; ++i) {
        scanf("%d", in + i);
    }
    for(int i = 0; i < n; ++i) {
        scanf("%d", pre + i);
    }

    //  构建树
    Tree * root = createTree(0, n - 1, 0, n - 1);

    for(int i = 0; i < m; ++i) {
        scanf("%d%d", &a, &b);

        bool fab[2] = {false, false};
        int nfnum = 2;
        for(int j = 0; j < n; ++j) {
            if(a == pre[j]) {
                fab[0] = true;
                --nfnum;
            }
            if(b == pre[j]) {
                fab[1] = true;
                --nfnum;
            }
        }


        if(nfnum > 0) {
            printf("ERROR:", nfnum);
            for(int j = 0; j < 2; ++j) {
                if(!fab[j]) {
                    if(nfnum == 2 && j == 1) {
                        printf("and");
                    }
                    printf(" %d ", j == 0? a : b);
                }
            }
            if(nfnum == 2) {
                printf("are");
            } else {
                printf("is");
            }

            printf(" not found.\n");
        } else {
            dfs(root);
        }
    }

    return 0;
}

//  pl代表先序遍历的左边界,pr代表先序遍历的右边界,
//  il和ir同理只不过是中序遍历的两个边界
Tree* createTree(int pl, int pr, int il, int ir) {
    if(pl > pr) {
        return NULL;
    }

    Tree * t = new Tree;
    t->key = pre[pl];

    int i;
    for(i = il; i <= ir; ++i) {
        if(in[i] == pre[pl]) {
            break;
        }
    }

    int len = i - il;
    t->lchild = createTree(pl + 1, pl + len, il, i - 1);
    t->rchild = createTree(pl + len + 1, pr, i + 1, ir);

    return t;
}

int dfs(Tree *& root) {
    //  如果root为NULL则返回-1
    if(root == NULL) {
        return -1;
    }

    //  findakey 标志当前节点的值是不是目标值
    bool findakey = false;
    if(root->key == a || root->key == b) {
        findakey = true;
    }

    //  从左右子节点中寻找目标值
    int lkey = dfs(root->lchild);
    int rkey = dfs(root->rchild);

    //  判断是不是左右子节点包含两个目标值
    if(lkey != -1 && rkey != -1) {
        printf("LCA of %d and %d is %d.\n", a, b, root->key);
        return -1;
    } else if(findakey && (lkey != -1 || rkey != -1 || a == b)) {
        //  判断是不是当前节点的值和其左右子节点中的一个包含目标值,也是就ancestor的情况
        //  并且还需要特别判断两个目标值是否相等,如果相等也要输出
        printf("%d is an ancestor of %d.\n", root->key, a == b ? a : lkey != -1 ? lkey : rkey);
        return -1;
    } else if(findakey) {
        //  如果只有根节点包含目标值 则返回目标值
        return root->key;
    } else if(lkey != -1 || rkey != -1) {
        //  如果左右子树中只有其一包含目标值,则返回目标值
        return lkey != -1 ? lkey : rkey;
    }

    //  其他情况返回未找到标志 -1
    return -1;
}

如有错误,欢迎指摘。

猜你喜欢

转载自blog.csdn.net/CrazyOnes/article/details/82596927