`

Lowest Common Ancestor of a Binary Tree

 
阅读更多

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

 

        _______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.

Hint:
Top-down or bottom-up? Consider both approaches and see which one is more efficient.

A Top-Down Approach (Worst case O(n2) ):
Let’s try the top-down approach where we traverse the nodes from the top to the bottom. First, if the current node is one of the two nodes, it must be the LCA of the two nodes. If not, we count the number of nodes that matches either p or q in the left subtree (which we call totalMatches). If totalMatches equals 1, then we know the right subtree will contain the other node. Therefore, the current node must be the LCA. If totalMatches equals 2, we know that both nodes are contained in the left subtree, so we traverse to its left child. Similar with the case where totalMatches equals 0 where we traverse to its right child.

 

// Return #nodes that matches P or Q in the subtree.
int countMatchesPQ(Node *root, Node *p, Node *q) {
  if (!root) return 0;
  int matches = countMatchesPQ(root->left, p, q) + countMatchesPQ(root->right, p, q);
  if (root == p || root == q)
    return 1 + matches;
  else
    return matches;
}
 
Node *LCA(Node *root, Node *p, Node *q) {
  if (!root || !p || !q) return NULL;
  if (root == p || root == q) return root;
  int totalMatches = countMatchesPQ(root->left, p, q);
  if (totalMatches == 1)
    return root;
  else if (totalMatches == 2)
    return LCA(root->left, p, q);
  else /* totalMatches == 0 */
    return LCA(root->right, p, q);
}
 

 

What is the run time complexity of this top-down approach?

First, just for fun, we assume that the tree contains n nodes and is balanced (with its height equals to log(n) ). In this case, the run time complexity would be O(n). Most people would guess a higher ordered complexity than O(n) due to the function countMatchesPQ() traverses the same nodes over and over again. Notice that the tree is balanced, you cut off half of the nodes you need to traverse in each recursive call of LCA() function. The proof that the complexity is indeed O(n) is left as an exercise to the reader.

What if the tree is not necessarily balanced? Then in the worst case the complexity could go up to O(n2). Why? Could you come up with such case? (Hint: The tree might be a degenerate tree).

A Bottom-up Approach (Worst case O(n) ):
Using a bottom-up approach, we can improve over the top-down approach by avoiding traversing the same nodes over and over again.

We traverse from the bottom, and once we reach a node which matches one of the two nodes, we pass it up to its parent. The parent would then test its left and right subtree if each contain one of the two nodes. If yes, then the parent must be the LCA and we pass its parent up to the root. If not, we pass the lower node which contains either one of the two nodes (if the left or right subtree contains either p or q), or NULL (if both the left and right subtree does not contain either p or q) up.

Sounds complicated? Surprisingly the code appears to be much simpler than the top-down one.

 

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root) return NULL;
  if (root == p || root == q) return root;
  Node *L = LCA(root->left, p, q);
  Node *R = LCA(root->right, p, q);
  if (L && R) return root;  // if p and q are on both sides
  return L ? L : R;  // either one of p,q is on one side OR p,q is not in L&R subtrees
}

 

Notes:

The LCA problem had been studied extensively by many computer scientists. There exists efficient algorithms for finding LCA in constant time after initial processing of the tree in linear time. For the adventurous reader, please read this article for more details: Range Minimum Query and Lowest Common Ancestor in Topcoder.

Further Thoughts:
What if each node in the binary tree has a link to its parent? Could you devise a non-recursive approach without using extra space?

 

From: 

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

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

分享到:
评论

相关推荐

    Binary Tree – Lowest Common Ancestor 题型总结

    Lowest Common Ancestor of a Binary Search Tree  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:...

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

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

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

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

    Lowest Common Ancestor of Deepest Leaves

    Given a rooted binary tree, return the lowest common ancestor of its deepest leaves. Recall that: The node of a binary tree is a leaf if and only if it has no children The depth of the root of ...

    yandex_tree_3.rar_tree

    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

    Algorithms-Leetcode-Javascript:Javascript中的算法解析。 Leetcode-Geeksforgeeks-职业生涯

    要在控制台中运行特定问题,请转至文件test,将调用添加到测试函数( test() ),然后在控制台node <problem> (例如, node LeetcodeProblems/Lowest_Common_Ancestor_of_a_Binary_Tree.js )。 Leetcode问题 名称...

    lrucacheleetcode-LeetCode_Java:力扣_Java

    Binary Lifting for LCA(lowest common ancestor) ---, 5.贪婪 6. Manacher/KMP算法 (未完成) 7. 添加 8. 指针 滑动窗口 9.前缀总和 10.递归/DFS 11.棘手的方法 (未完成) 12. 堆栈 Monotonic_Stack 13. 14. ...

    Lowest Common Denominator Bible-开源

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

    8-1student_C++_CodeName_

    8-1 Students I (10分)Write a program that asks you 10 records of students. Each record consists of a name (w/o space) and scores for three courses (in integer 1 to 5). Output a list as following and ...

    Computer System Design System-on-Chip

    It begins with a global introduction, from the high-level view to the lowest common denominator (the chip itself), then moves on to the three main building blocks of an SOC (processor, memory, and ...

    微软内部资料-SQL性能优化5

    On a qualified select, update, or delete, the correct leaf page will be the lowest page of the tree in which one or more rows with the specified key or keys reside. A qualified operation is one that ...

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

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

    mpeg7 CE1常用形状识别数据集

    The shapes are defined by a binary mask outlining the objects. The evaluation protocol for this retrieval task is the bullseye rating, in which each image is used as reference and compared to all of ...

    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)> algorithm for the restricted RMQ 60 5.1.6 An AC programme 61 5.2 最长公共子序列LCS ...

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

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

    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)> algorithm for the restricted RMQ 60 5.1.6 An AC programme 61 5.2 最长公共子序列LCS ...

    Thomas H Lee THE DESIGN OF LOW NOISE OSCILLATORS

    Clearly, there is a need for a deep understanding of the fundamental mechanisms governing the process by which device, substrate, and supply noise turn into jitter and phase noise. Existing models ...

    arty_a7_sch.pdf

    to enable a common design to scale across families for optimal power, performance, and cost. The Spartan®-7 family is the lowest density with the lowest cost entry point into the 7 series portfolio...

    Perspective: Basic understanding of condensed phases of matter

    Packing problems have been a source of fascination for millennia and their study has produced a rich literature that spans numerous disciplines. Investigations of hard-particle packing models have ...

Global site tag (gtag.js) - Google Analytics