`

Lowest Common Ancestor of BST

 
阅读更多

Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.

 

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

Using the above tree as an example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. But how about LCA of nodes 2 and 4? Should it be 6 or 2?

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes vand w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” Since a node can be a descendant of itself, the LCA of 2 and 4 should be 2, according to this definition.

Hint:
A top-down walk from the root of the tree is enough.

Solution:
There’s only three cases you need to consider.

  1. Both nodes are to the left of the tree.
  2. Both nodes are to the right of the tree.
  3. One node is on the left while the other is on the right.

For case 1), the LCA must be in its left subtree. Similar with case 2), LCA must be in its right subtree. For case 3), the current node must be the LCA.

Therefore, using a top-down approach, we traverse to the left/right subtree depends on the case of 1) or 2), until we reach case 3), which we concludes that we have found the LCA.

A careful reader might notice that we forgot to handle one extra case. What if the node itself is equal to one of the two nodes? This is the exact case from our earlier example! (The LCA of 2 and 4 should be 2). Therefore, we add case number 4):

4. When the current node equals to either of the two nodes, this node must be the LCA too.

The run time complexity is O(h), where h is the height of the BST. Translating this idea to code is straightforward (Note that we handle case 3) and 4) in the else statement to save us some extra typing ):

/* 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;
}

You should realize quickly that the above code contains tail recursion. 

Time complexity of above solution is O(h) where h is height of tree. Also, the above solution requires O(h) extra space in function call stack for recursive function calls. We can avoid extra space using iterative solution.

struct node* LCA(struct node* root, int n1, int n2) {
    while (root != NULL) {
         // If both n1 and n2 are smaller than root, then LCA lies in left
        if (root->data > n1 && root->data > n2)
           root = root->left;
 
        // If both n1 and n2 are greater than root, then LCA lies in right
        else if (root->data < n1 && root->data < n2)
           root = root->right;
 
        else break;
    }
    return root;
}

Reference:

http://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/

http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-search-tree.html

分享到:
评论

相关推荐

    Binary Tree – Lowest Common Ancestor 题型总结

     Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined ...

    算法面试通关40讲完整课件 18-20 树、二叉树、二叉搜索树

    3. **二叉树的最近公共祖先 (Lowest Common Ancestor of a Binary Tree)**:这个是在非二叉搜索树的情况下的类似问题,通常需要额外的策略来处理。 为了有效地解决这些问题,你需要熟悉二叉搜索树的遍历方法,包括...

    acm模板(全)

    5.1.2 Lowest Common Ancestor (LCA) 53 5.1.3 Reduction from LCA to RMQ 56 5.1.4 From RMQ to LCA 57 5.1.5 An(N), O(1)&gt; algorithm for the restricted RMQ 60 5.1.6 An AC programme 61 5.2 最长公共子序列LCS ...

    【POJ1330】最近公共祖先(LCA):并查集+深搜 - cxllyg的专栏 - 博客频道 - CSDN.NET1

    最近公共祖先(Lowest Common Ancestor,简称LCA)是指在一颗树中,两个指定节点的最近的共同祖先。这个问题在计算机科学,尤其是数据结构和算法领域中非常常见,特别是在处理二叉树时。本文将详细探讨三种不同情况...

    手稿_V1.093

    在给定的文件中,我们讨论的是一个与计算机科学相关的编程问题,具体是关于二叉搜索树(Binary Search Tree, BST)的最近公共祖先(Lowest Common Ancestor, LCA)问题。这个问题来源于LeetCode的一个挑战,其目标是...

    斯坦福大学数据结构

    8. 最近公共祖先(Lowest Common Ancestor, LCA)问题:LCA问题是寻找两节点在树结构中的最近公共祖先节点。该问题在计算机科学中有着广泛的应用,如网络路由、图形编辑器等。 在实际应用中,选择合适的数据结构...

    刘汝佳 高级数据结构

    #### RMQ(Range Minimum Query)与 LCA(Lowest Common Ancestor) - **RMQ**: - 区间最小值查询问题,即给定一个数组和若干查询区间,每次查询都需要返回该区间内的最小值。 - 解决方案包括线段树、树状数组...

    刘汝佳高级数据结构教程

    - **LCA (Lowest Common Ancestor)**:最低公共祖先问题,是指在一棵树中找到两个节点的最近公共祖先。 以上是刘汝佳高级数据结构教程中关于平衡二叉树、AVL树、伸展树、可并优先队列、线段树、树状数组、RMQ与LCA...

    高级数据结构-----刘汝佳

    **LCA(Lowest Common Ancestor)**是最近公共祖先问题,即给定一棵树和两个节点,找到这两个节点的最近公共祖先。常用的求解方法包括预处理法、倍增法等。 以上就是《高级数据结构》一书中所介绍的关键知识点,涵盖...

    tree:流行树算法的Javascript实现

    7. **最近公共祖先(Lowest Common Ancestor, LCA)**:查找给定两个节点在树中的最近公共祖先。 在实际的"tree-master"项目中,可能包含了这些算法的实现,以及用于测试和展示的示例数据。通过阅读和学习这些代码,...

    深入二叉树两个结点的最低共同父结点的详解

    二叉树中的最低共同父结点(Lowest Common Ancestor, LCA)是指在二叉树结构中,两个指定结点的最近公共祖先。在二叉树中寻找两个结点的最低共同父结点是一个常见的算法问题,尤其在数据结构和算法的面试中经常出现...

    ACM必备内容(几乎全)!!!

    - **Lowest Common Ancestor (LCA)**:最近公共祖先问题。 - **RMQ to LCA**:将RMQ问题转化为LCA问题。 ##### 5.2 最长公共子序列(LCS) 最长公共子序列是在两个序列中找到最长的共同子序列。 ##### 5.3 最长上升...

Global site tag (gtag.js) - Google Analytics