PAT 甲级 刷题日记|A 1143 Lowest Common Ancestor (30 分)

单词积累

respectively 分别地 各自地

descendants 后代 晚辈 子节点

题目

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.

A binary search tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Given any two nodes in a BST, 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 BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. 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 BST, 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
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
结尾无空行

Sample Output:

LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
结尾无空行

思路

求二叉排序树的最低公共父节点,常规思路是从根节点开始遍历,遍历到第一个能把两个数从中间分开的节点,就找到了结果。但是该条思路有两个测试样例(3和4)超时了。不过作为一般思路,仍有借鉴意义。

通过研究题解,发现有更巧妙的做法,无需建树。题目给定了前序序列和待查询数a和b,遍历前序序列,找到第一个大小位于a和b间的数,就是结果。该做法全篇无树,但又巧用树的性质,解决了树的问题。

为什么是第一个呢?因为前序序列,遇到的首先是根,这个根会把后续的树分成左右子树,a和b也会被分开,不会再出现共同的父节点。

代码(AC版本)

#include<bits/stdc++.h>
using namespace std;

map<int, bool> mp;

int main() {
    int m, n, u, v, a;
    scanf("%d %d", &m, &n);
    vector<int> pre(n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &pre[i]);
        mp[pre[i]] = true;
    }
    while (m--) {
        scanf("%d %d", &u, &v);
        for (int j = 0; j < n; j++) {
            a = pre[j];
            if ((a >= v && a <= u) || (a >= u && a <= v)) break;
        }
        if (mp[u] == false && mp[v] == false)
            printf("ERROR: %d and %d are not found.\n", u, v);
        else if (mp[u] == false || mp[v] == false)
            printf("ERROR: %d is not found.\n", mp[u] == false ? u : v);
        else if (a == u || a == v)
            printf("%d is an ancestor of %d.\n", a, a == u ? v : u);
        else
            printf("LCA of %d and %d is %d.\n", u, v, a);
    }
}

代码2(常规超时版)

#include <bits/stdc++.h>
using namespace std;

int N, M;
const int maxn = 10003;
int num[maxn];
map<int,int> vis;
vector<int> ans;

struct node{
    int data;
    node* lchild;
    node* rchild;
    node(int d): data(d), lchild(NULL), rchild(NULL) {
    }
};

void insert(node* &root, int v) {
    if (root == NULL) {
        root = new node(v);
        return;
    }
    if (v < root->data) {
        insert(root->lchild, v);
    } else if (v >= root->data) {
        insert(root->rchild, v);
    }
}

void search(node* root, int a, int b) {
    if (a == root->data) {
        printf("%d is an ancestor of %d.\n", a, b);
        return;
    }else if (b == root->data) {
        printf("%d is an ancestor of %d.\n", b, a);
        return;
    }else if (a < root->data && b < root->data) {
        search(root->lchild, a, b);
    } else if (a > root->data && b > root->data) {
        search(root->rchild, a, b);
    } else {
        printf("LCA of %d and %d is %d.\n", a, b, root->data);
    }
}


int main() {
    cin>>N>>M;
    node* root = NULL;
    for (int i = 0; i < M; i++) {
        cin>>num[i];
        vis[num[i]] = 1;
        insert(root, num[i]);
    }
    while (N--) {
        int n1, n2;
        cin>>n1>>n2;
        if (vis[n1] == 1 && vis[n2] == 1) {
            search(root, n1, n2);
        } else if (vis[n1] == 1) {
            printf("ERROR: %d is not found.\n", n2);
        } else if (vis[n2] == 1) {
            printf("ERROR: %d is not found.\n", n1);
        } else {
            printf("ERROR: %d and %d are not found.\n", n1, n2);
        }
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容