`

Lowest Common Ancestor with Parent Node

 
阅读更多

Given a binary tree, find the lowest common ancestor of two given nodes in the tree. Each node contains a parent pointer which links to its parent.


Note:
This is Part II of Lowest Common Ancestor of a Binary Tree. If you need to find the lowest common ancestor without parent pointers, please read Lowest Common Ancestor of a Binary Tree Part I.

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous post:Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.

In my last post: Lowest Common Ancestor of a Binary Tree Part I, we have devised a recursive solution which finds the LCA in O(n) time. If each node has a pointer that link to its parent, could we devise a better solution?

Hint:
No recursion is needed. There is an easy solution which uses extra space. Could you eliminate the need of extra space?

An easy solution:
As we trace the two paths from both nodes up to the root, eventually it will merge into one single path. The LCA is the exact first intersection node where both paths merged into a single path. An easy solution is to use a hash table which records visited nodes as we trace both paths up to the root. Once we reached the first node which is already marked as visited, we immediately return that node as the LCA.

Node *LCA(Node *root, Node *p, Node *q) {
  hash_set<Node *> visited;
  while (p || q) {
    if (p) {
      if (!visited.insert(p).second)
        return p; // insert p failed (p exists in the table)
      p = p->parent;
    }
    if (q) {
      if (!visited.insert(q).second)
        return q; // insert q failed (q exists in the table)
      q = q->parent;
    }
  }
  return NULL;
}

The run time complexity of this approach is O(h), where h is the tree’s height. The space complexity is also O(h), since it can mark at most 2h nodes.

The best solution:
A little creativity is needed here. Since we have the parent pointer, we could easily get the distance (height) of both nodes from the root. Once we knew both heights, we could subtract from one another and get the height’s difference (dh). If you observe carefully from the previous solution, the node which is closer to the root is alwaysdh steps ahead of the deeper node. We could eliminate the need of marking visited nodes altogether. Why?

The reason is simple, if we advance the deeper node dh steps above, both nodes would be at the same depth. Then, we advance both nodes one level at a time. They would then eventually intersect at one node, which is the LCA of both nodes. If not, one of the node would eventually reach NULL (root’s parent), which we conclude that both nodes are not in the same tree. However, that part of code shouldn’t be reached, since the problem statement assumed that both nodes are in the same tree.

int getHeight(Node *p) {
  int height = 0;
  while (p) {
    height++;
    p = p->parent;
  }
  return height;
}
 
// As root->parent is NULL, we don't need to pass root in.
Node *LCA(Node *p, Node *q) {
  int h1 = getHeight(p);
  int h2 = getHeight(q);
  // swap both nodes in case p is deeper than q.
  if (h1 > h2) {
    swap(h1, h2);
    swap(p, q);
  }
  // invariant: h1 <= h2.
  int dh = h2 - h1;
  for (int h = 0; h < dh; h++)
    q = q->parent;
  while (p && q) {
    if (p == q) return p;
    p = p->parent;
    q = q->parent;
  }
  return NULL;  // p and q are not in the same tree
}

From:

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

分享到:
评论

相关推荐

    Range Minimum Query and Lowest Common Ancestor[翻译]1

    Range Minimum Query (RMQ) 和 Lowest Common Ancestor (LCA) 是两种在计算机科学和算法设计中常见的数据结构和问题。在这篇文章的翻译中,主要介绍了这两种概念以及它们的关联和解决方案。 首先,Range Minimum ...

    1123.Lowest Common Ancestor of Deepest Leaves最深叶节点的最近公共祖先【LeetCode单题讲解系列】

    1123.Lowest_Common_Ancestor_of_Deepest_Leaves最深叶节点的最近公共祖先【LeetCo

    Binary Tree – Lowest Common Ancestor 题型总结

    Lowest Common Ancestor of a Binary Search Tree ...According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has b

    Lowest Common Ancestor of Deepest Leaves

    在给定的问题中,我们需要解决的是“最低共同祖先(Lowest Common Ancestor, LCA)”问题,但针对的是二叉树中最深叶子节点。这是一个经典的计算机科学问题,特别是在数据结构和算法领域。二叉树是一种特殊的树结构...

    c语言-leetcode题解之0235-lowest-common-ancestor-of-a-binary-search

    c c语言_leetcode题解之0235_lowest_common_ancestor_of_a_binary_search

    c语言-leetcode题解之0236-lowest-common-ancestor-of-a-binary-tree

    c c语言_leetcode题解之0236_lowest_common_ancestor_of_a_binary_tree

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

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

    最近公共祖先LCA(C++版).docx

    最近公共祖先(Lowest Common Ancestor,LCA) 最近公共祖先(Lowest Common Ancestor,LCA)是指在一棵树上,两个节点的最近公共祖先节点。也就是说,两个点在这棵树上的距离最近的公共祖先节点。LCA 是一个基本...

    郭华阳《RMQ与LCA问题》

    **RMQ(Range Minimum Query)与LCA(Lowest Common Ancestor)问题**是图论与数据结构领域中的两个重要概念,广泛应用于算法设计和优化。这篇由郭华阳所著的国家队论文深入探讨了这两个问题及其解决方案。 **RMQ...

    ACM2020倍增+LCA.pdf

    本资源主要涉及到两方面的知识点:ST表(Sparse Table)和LCA(Lowest Common Ancestor)。 ST表 ST表是一种预处理数据结构,用于解决Range Query问题,即在一个数组中查询一个范围内的最大或最小值。ST表的主要...

    Lowest Common Denominator Bible-开源

    非技术人员(包括传教士/儿童/老年人)的简单圣经免费软件小 1.2 兆下载与 OT+NT。 &lt; 1 秒启动和搜索甚至在过时的最低公分母 486 上(1 GB 高清、640*480 分辨率、16 mb 内存、无 CD、28.8 调制解调器、Win95)

    js代码-查找两个节点的最近的一个共同父节点,可以包括节点自身 oNode1 和 oNode2 在同一文档中,且不会为相同的节点

    在JavaScript中,查找两个节点的最近公共父节点(Lowest Common Ancestor,LCA)是一项常见的任务,尤其在处理DOM树或数据结构时。这里我们将深入探讨如何实现这个功能,并结合给定的`main.js`文件和`README.txt`来...

    手稿_V1.093

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

    面向XML关键字查询的高效RKN求解策略

    针对已有方法不能正确求解基于ELCA(exclusive lowest common ancestor)语义的相关关键字节点(RKN,relevant keyword node)的问题,提出RKN的形式化定义及相应的RKN-Base算法。该算法通过顺序扫描每个关键字节点一次...

    lrucacheleetcode-LeetCode_Java:力扣_Java

    LCA(lowest common ancestor) ---, 5.贪婪 6. Manacher/KMP算法 (未完成) 7. 添加 8. 指针 滑动窗口 9.前缀总和 10.递归/DFS 11.棘手的方法 (未完成) 12. 堆栈 Monotonic_Stack 13. 14. 数据结构 每周比赛 第一...

    LOWEST_LOW_VALUE - MetaTrader 5脚本.zip

    《MetaTrader 5脚本——LOWEST_LOW_VALUE深入解析》 在金融交易领域,MetaTrader 5(MT5)是一款广泛使用的交易平台,以其强大的图表分析、自动化交易和多元化金融市场接入功能而深受投资者喜爱。今天我们将深入...

    tictax:Web服务的流序列分类✓:pushpin:

    tictax:Web服务的流序列分类 使用One Codex和EBI API从命令行或Python快速便捷地实现最低的祖先(LCA)分配。 以正确的方向吹风,每秒可发出约100个请求。... kmer-lca Lowest common ancestor sequ

    二叉树最近最近公共祖先

    在二叉树中,最近公共祖先(最近共同祖先,LCA,Lowest Common Ancestor)是指两个节点在树中的最近的共同父节点。在某些应用场景,如文件系统或社交网络中,找到最近公共祖先具有重要意义。 针对给定的"二叉树最近...

    mcd.zip_The Common

    This program calculates the lowest common multiple of two numbers using Euclid s algorithm. To do this we will read the two numbers and we do accounts required to calculate

    RMQ & LCA 问题及其相互关系

    在算法领域,Range Minimum Query (RMQ) 和 Lowest Common Ancestor (LCA) 问题不仅因其自身的挑战性而受到关注,更因为它们在字符串处理、计算生物学以及其他复杂数据结构中的广泛应用而显得尤为重要。本文将深入...

Global site tag (gtag.js) - Google Analytics