//求两个结点的最低公共祖先最低公共祖先,即 LCA(Lowest Common Ancestor)//
//复杂性和 n 同样数量级
BTree FindLCA(BTree T, BTree target1, BTree target2)
{
if (T == NULL)
return NULL;
//cout<<"vist"<<T->data<<endl;
if (T == target1 || T == target2)
return T;
BTree left = FindLCA(T->lchild, target1, target2);
BTree right = FindLCA(T->rchild, target1, target2);
if (left && right) // 分别在左右子树
return T;
return left ? left : right; // 都在左子树或右子树
}
//10 求任意两结点距离
//首先找到两个结点的 LCA,然后分别计算 LCA 与它们的距离,最后相加即可。
int FindLevel(BTree node, BTree target)
{
if (node == NULL)
return -1;
if (node == target)
return 0;
int level = FindLevel(node->lchild, target); // 先在左子树找
if (level == -1)
level = FindLevel(node->rchild, target); // 如果左子树没找到,在右子树找
if (level != -1) // 找到了,回溯
return level + 1;
return -1; // 如果左右子树都没找到
}
int DistanceNodes(BTree node, BTree target1,BTree target2)
{
BTree lca = FindLCA(node, target1, target2); // 找到最低公共祖先结点
int level1 = FindLevel(lca, target1);
int level2 = FindLevel(lca, target2);
return level1 + level2;
}
|