思路:当遇到一个结点是返回1,当左右子树都返回1的时候,即最小公共父节点。
//二叉树的数据结构
typedef struct MyStruct
{
char data;
struct MyStruct *leftChild;
struct MyStruct *rightChild;
}Node, *Tree;
//查找方法
int findFirstFather(Tree root, char first, char second,char &destination){
int i, j;
if (root==NULL)
{
return 0;
}
if (root->data == first || root->data == second)
{
return 1;
}
else
{
i = findFirstFather(root->leftChild, first, second, destination);
j = findFirstFather(root->rightChild, first, second, destination);
if (i == 1 && j == 1)
{
destination = root->data;
}
if (i||j)
{
return 1;
}
}
return 0;
}
输入:ABC##DE#G##F###
输出:D
时间: 2024-10-14 15:21:45