1151 LCA in a Binary Tree(30 分)

本文介绍了一种算法,用于在给定的二叉树中找到两个节点的最低公共祖先(LCA)。通过输入二叉树的中序遍历和前序遍历序列,该算法能唯一确定树的结构,并对每一对节点进行LCA查找。文章提供了详细的C++代码实现,包括树的构建、节点搜索和LCA计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

C++:

/*
 @Date    : 2018-09-11 09:07:02
 @Author  : 酸饺子 (changzheng300@foxmail.com)
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856
 */

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

struct TreeNode
{
    TreeNode *left = nullptr, *right = nullptr;
    int key;
    TreeNode *father = nullptr;
    int level;
};

int M, N;
const int MAXN = 10005;
int pre[MAXN], in[MAXN];

TreeNode* build_tree(int preB, int preE, int inB, int inE)
{
    if (preB == preE)
        return nullptr;
    TreeNode *r = new TreeNode;
    r->key = pre[preB];
    if (preB + 1 == preE)
        return r;
    int leftE;
    for (int i = inB; i != inE; ++i)
    {
        if (in[i] == pre[preB])
        {
            leftE = i;
            break;
        }
    }
    r->left = build_tree(preB + 1, preB + 1 + leftE - inB, inB, leftE);
    if (r->left)
        r->left->father = r;
    r->right = build_tree(preB + 1 + leftE - inB, preE, leftE + 1, inE);
    if (r->right)
        r->right->father = r;
    return r;
}

TreeNode* search(TreeNode *T, int c, int level)
{
    if (!T)
        return nullptr;
    if (T->key == c)
    {
        T->level = level;
        return T;
    }
    else
    {
        TreeNode *lRes = search(T->left, c, level + 1);
        if (lRes)
            return lRes;
        else
        {
            TreeNode *rRes = search(T->right, c, level + 1);
            return rRes;
        }
    }
}

int main()
{
    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]);

    TreeNode *T = nullptr;
    T = build_tree(0, N, 0, N);
    while (M--)
    {
        int c1, c2;
        scanf("%d %d", &c1, &c2);
        TreeNode *r1 = search(T, c1, 1), *r2 = search(T, c2, 1);
        if (r1 && r2)
        {
            int res = -1;
            int tempC1 = c1, tempC2 = c2;
            if (r1->level < r2->level)
            {
                swap(r1, r2);
                swap(tempC1, tempC2);
            }
            int dLevel = r1->level - r2->level;
            for (int i = 0; i != dLevel; ++i)
                r1 = r1->father;
            while (r1 != r2)
            {
                r1 = r1->father;
                r2 = r2->father;
            }
            res = r1->key;
            if (res == tempC1)
                printf("%d is an ancestor of %d.\n", tempC1, tempC2);
            else if (res == tempC2)
                printf("%d is an ancestor of %d.\n", tempC2, tempC1);
            else
                printf("LCA of %d and %d is %d.\n", c1, c2, res);
        }
        else if (r2)
        {
            printf("ERROR: %d is not found.\n", c1);
        }
        else if (r1)
        {
            printf("ERROR: %d is not found.\n", c2);
        }
        else
        {
            printf("ERROR: %d and %d are not found.\n", c1, c2);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值