美文网首页
求取两个节点的最近邻祖先

求取两个节点的最近邻祖先

作者: lintong | 来源:发表于2015-02-28 15:26 被阅读37次

Given values of two nodes in a Binary Search Tree, write a c program to find the Lowest Common Ancestor (LCA). You may assume that both the values exist in the tree.

对LCA的解释

Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as **the lowest node in T that has both n1 and n2 as descendants **(where we allow a node to be a descendant of itself).
The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor

解决思路

对于二叉排序树,可以利用元素的性质简化结题方法。

/* Function to find LCA of n1 and n2. The function assumes that both
   n1 and n2 are present in BST */
struct node *lca(struct node* root, int n1, int n2)
{
    if (root == NULL) return NULL;
 
    // If both n1 and n2 are smaller than root, then LCA lies in left
    if (root->data > n1 && root->data > n2)
        return lca(root->left, n1, n2);
 
    // If both n1 and n2 are greater than root, then LCA lies in right
    if (root->data < n1 && root->data < n2)
        return lca(root->right, n1, n2);
 
    return root;
}

但如果这棵树不是二叉查找树,只是一棵普通的二叉树呢?由于每个结点都有一个指针指向它的父结点,于是我们可以从任何一个结点出发,得到一个到达树根结点的单向链表。因此这个问题转换为两个单向链表的第一个公共结点。

相关文章

  • 求取两个节点的最近邻祖先

    Given values of two nodes in a Binary Search Tree, write ...

  • LCA_最近公共祖先

    LCA 最近公共祖先在一棵没有环的树上,每个节点肯定有其父亲节点和祖先节点,而最近公共祖先,就是两个节点在这棵树上...

  • lintcode 最近公共祖先

    给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。最近公共祖先是两个节点的公共的祖先节点且具有最大深度。样例...

  • LCA(最近公共祖先)算法

    在一棵没有环的树上,每个节点肯定有其父亲节点和祖先节点,而最近公共祖先,就是两个节点在这棵树上深度最大的公共的祖先...

  • 最近公共祖先(LCA-tarjan/RMQ/倍增)

    在一棵没有环的树上,每个节点肯定有其父亲节点和祖先节点,而最近公共祖先,就是两个节点在这棵树上深度最大的公共的祖先...

  • 小米-基础算法-最近公共祖先

    给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。两个节点的最近公共祖先,是指两个节点的所有父...

  • 算法—— 最近公共祖先 III

    给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。两个节点的最近公共祖先,是指两个节点的所有父...

  • 236. Lowest Common Ancestor of a

    求两个节点最近的祖先节点,思路是找到根节点到所求节点的路径,那么两条路径分叉处就是祖先节点递归,假定root不是p...

  • 236. Lowest Common Ancestor of a

    求两个节点最近的祖先节点,思路是找到根节点到所求节点的路径,那么两条路径分叉处就是祖先节点递归,假定root不是p...

  • 最近公共祖先系列

    最近公共祖先I 描述: 给定一棵二叉树,找到两个节点的最近公共父节点 (LCA)。最近公共祖先是两个节点的公共的祖...

网友评论

      本文标题:求取两个节点的最近邻祖先

      本文链接:https://www.haomeiwen.com/subject/mgwpxttx.html