问题 L: DS_6.12 最近共同祖先(by Yan)
时间限制: 15 Sec 内存限制: 128 MB
提交: 366 解决: 262
[提交] [状态] [讨论版] [命题人:zengyan]
题目描述
从键盘接收扩展先序序列,以二叉链表作为存储结构,建立二叉树。求两个不同结点ch1,ch2的最近共同祖先。
第一行:扩展先序序列
第二行:ch1,ch2两个不同结点值,用一个空格间隔。
样例输入 Copy
ABC##DE#G##F### C F
样例输出 Copy
B
#include <stdlib.h>
#include <stdio.h>
typedef struct tree {
char data;
struct tree *rchild;
struct tree *lchild;
} Node, *BTree;
typedef struct A {
char arr[20];
int deep;
} Arr;
Arr arrays[20];
void creat(BTree *root) {
char ch;
ch = getchar();
*root = (BTree) malloc(sizeof(Node));
if (ch == '#') {
*root = NULL;
} else {
(*root)->data = ch;
creat(&(*root)->lchild);
creat(&(*root)->rchild);
}
}
char save[100];
int count = 0;
void fun(BTree root, int deepth) {
if (root) {
save[deepth] = root->data;
if (root->lchild == NULL && root->rchild == NULL) {
count++;
arrays[count].deep = deepth;
for (int i = 0; i <= deepth; i++) {
arrays[count].arr[i] = save[i];
}
}
if (root->lchild) {
fun(root->lchild, deepth + 1);
}
if (root->rchild) {
fun(root->rchild, deepth + 1);
}
}
}
int main() {
BTree root = (BTree) malloc(sizeof(Node));
creat(&root);
fun(root, 0);
int howmany = 0;
int x = 0;
int y = 0;
char data1,data2;
getchar();
// printf("the first:");
data1 = getchar();
getchar();
// printf("the second:");
data2 = getchar();
for (int i = 1; i <= count; i++) {
for (int j = 0; j <= arrays[i].deep + 1; ++j) {
// cout << arrays[i].arr[j];
if(arrays[i].arr[j]==arrays[x].arr[y]){
continue;
}
if (arrays[i].arr[j] == data1 || arrays[i].arr[j] == data2) {
howmany++;
if(howmany == 2){
printf("%c",arrays[x].arr[y-1]);
exit(0);
}
x = i;
y = j;
}
}
// cout << endl;
}
return 0;
}