【问题描述】假设二叉树采用二叉链表方式存储,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;
}