2. 二叉树结点的共同祖先问题

【问题描述】假设二叉树采用二叉链表方式存储,root指向根结点,p所指结点和q所指结点为二叉树中的两个不同结点,且互不成为根到该结点的路径上的点,编程求解距离它们最近的共同祖先。

【输入形式】二叉树的前序和中序遍历序列,用以创建该二叉树的链式存储结构;以及二叉树的两个结点数据 x 和 y

【输出形式】结点数据值为 x 和结点数据值为 y 的最近的共同祖先,若没有共同祖先则输出NULL,请注意一个结点本身不能成为另一个结点的共同祖先。

【样例输入】

GABDCEF

BDAEFCG

DF

【样例输出】

A

#include <iostream>
using namespace std;
#include <cstring>
#include <queue>
struct node
{
    char data;
    node *lchild;
    node *rchild;
};
char mid[1001], pre[1001];
node *build(int x, int y, int q, int p) // xy为前序序列的左右边界,qp为前序序列的左右边界
{
    int i;
    if (x > y || q > p)
        return NULL;
    node *root = new node;
    root->data = pre[x];
    root->lchild = NULL;
    root->rchild = NULL;
    for (i = q; i <= p; i++)
        if (pre[x] == mid[i])
            break;
    root->lchild = build(x + 1, x + i - q, q, i - 1);
    root->rchild = build(x + i - q + 1, y, i + 1, p);
    return root;
}
node *dfs(node *root, node *p, node *q)
{
    if (!root)
        return NULL;
    if (root->data == p->data || root->data == q->data)
        return root;
    node *l = dfs(root->lchild, p, q);
    node *r = dfs(root->rchild, p, q);
    if (l && r)
        return root;
    if (l)
        return l;
    if (r)
        return r;
    return NULL;
}
int main()
{
    cin >> pre >> mid;
    int len = strlen(mid);
    node *root;
    root = build(0, len - 1, 0, len - 1);
    char a, b;
    cin >> a >> b;
    node *t1 = new node;
    node *t2 = new node;
    node *ss = new node;
    t1->data = a;
    t2->data = b;
    ss = dfs(root, t1, t2);
    if (ss != NULL && ss->data != root->data)
    {
        cout << ss->data;
    }
    else
        cout << "NULL";
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wrong Ansewer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值