关于这道题,可以将其转化为求两个单链表的第一个焦点,这种做法需要两个栈,分别存储根节点到给定节点的路径。
下面给出新的解法,利用后根遍历,代码如下:
bool findCommonFather(treenode *root, char a, char b) //a不一定是左节点,b不一定是右节点
{
bool left = false, right = false;
if(root->lchild != NULL)
{
left = findCommonFather(root->lchild, a, b);
}
if(root->rchild != NULL)
{
right = findCommonFather(root->rchild, a, b);
}
if(root->data == a)
{
if(left)
{
right = true;
}
else
{
left = true;
}
}
else if(root->data == b)
{
if(right)
{
left = true;
}
else
{
right = true;
}
}
if(left && right)
{
cout<<root->data<<endl;
}
return left || right;
}
本文介绍了一种寻找二叉树中指定两个节点最近公共祖先的方法。通过递归遍历的方式,利用后根遍历的特性来找到这两个节点的最近公共祖先节点。这种方法不需要额外的数据结构辅助,仅通过递归调用即可实现。
1173

被折叠的 条评论
为什么被折叠?



