问题:已知二叉树root和两个节点p和q,要求找出p和q在root中的最早的共同祖先。要求:该二叉树的节点没有parent指针(如果有parent指针,算法会简单很多)。
算法思想:中序访问二叉树,对于当前节点,当其左子树和右子树访问完毕,且p与q都已经访问过,则当前节点就是p与q的共同祖先。
算法伪码:
commonAncestor = null;
int inorder(node)
{
if (node == null)
return 0;
if (commonAncesotr) // found
return 0;
// 处理左子树
int left = inorder(node->l);
// 处理当前节点
int in = 0;
if (node == p || node == q)
in = 1;
// 处理右子树
int right = inorder(node->r);
int sum = left + in + right;
// 左右子树都处理完毕,当前节点也处理完毕。检查sum,如果sum == 2,说明p和q都访问过了,当前节点就是commonAncestor。
if (sum == 2)
{
commonAncestor = node;
return 0;
}
return sum;
}
算法思想:中序访问二叉树,对于当前节点,当其左子树和右子树访问完毕,且p与q都已经访问过,则当前节点就是p与q的共同祖先。
算法伪码:
commonAncestor = null;
int inorder(node)
{
if (node == null)
return 0;
if (commonAncesotr) // found
return 0;
// 处理左子树
int left = inorder(node->l);
// 处理当前节点
int in = 0;
if (node == p || node == q)
in = 1;
// 处理右子树
int right = inorder(node->r);
int sum = left + in + right;
// 左右子树都处理完毕,当前节点也处理完毕。检查sum,如果sum == 2,说明p和q都访问过了,当前节点就是commonAncestor。
if (sum == 2)
{
commonAncestor = node;
return 0;
}
return sum;
}
本文介绍了一种在没有parent指针的二叉树中寻找两个节点最早共同祖先的算法。通过中序遍历的方式,当左右子树访问完毕且目标节点都被访问过时,即找到了共同祖先。
870

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



