【问题描述】
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树。例如如下的先序遍历字符串:ABC##DE#G##F### ,其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再计算任意两个结点的最近公共祖先,输出共同祖先。
【输入形式】
1、输入包括1行字符串,长度不超过100。
2、两个节点
【输出形式】
可能有多组测试数据,对于每组数据,输出共同祖先字符。
【样例输入】
abc##de#g##f###
c f
【样例输出】
b
【样例说明】
【评分标准】
参考了一些大佬的代码后受到启发:c++版如下
#include<iostream>
#include<vector>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
void CreateBiTree(BiTree* T)
{
char ch;
cin >> ch;
if (ch == '#')
*T = NULL;
else
{
*T = (BiTree)malloc(sizeof(BiTNode));
if (!*T)
exit(0);
(*T)->data = ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
bool findPath(BiTNode* root, vector<char>& path, char k)
{
if (root == NULL) return false;
path.push_back(root->data);
if (root->data == k)
return true;
if ((root->lchild && findPath(root->lchild, path, k)) ||
(root->rchild && findPath(root->rchild, path, k)))
return true;
path.pop_back();
return false;
}
void findLCA(BiTNode* root, char n1, char n2)
{
vector<char> path1, path2;
if (!findPath(root, path1, n1) || !findPath(root, path2, n2))
cout << "NULL";
int i;
for (i = 0; i < path1.size() && i < path2.size(); i++)
if (path1[i] != path2[i])
break;
cout << path1[i - 1];
}
int main()
{
BiTree T;
CreateBiTree(&T);
char a1, a2;
cin >> a1 >> a2;
findLCA(T, a1, a2);
return 0;
}