{"id":33770,"date":"2024-11-01T09:20:11","date_gmt":"2024-11-01T09:20:11","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33770"},"modified":"2024-11-01T11:46:45","modified_gmt":"2024-11-01T11:46:45","slug":"python-coding-test-course-finding-the-lowest-common-ancestor-2","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33770\/","title":{"rendered":"Python Coding Test Course, Finding the Lowest Common Ancestor 2"},"content":{"rendered":"<p><body><\/p>\n<p>\n    In this article, we will explore one of the problems related to finding the &#8216;Lowest Common Ancestor (LCA)&#8217; called &#8216;Finding the Lowest Common Ancestor 2&#8217;. This problem involves finding the lowest common ancestor of two nodes in a specific tree structure, particularly in a binary tree. The LCA problem is a fundamental problem associated with tree traversal and manipulation, frequently appearing in coding interviews and algorithm competitions.\n<\/p>\n<h2>Problem Description<\/h2>\n<p>\n    Given a binary tree, we need to find the lowest common ancestor of two nodes <code>u<\/code> and <code>v<\/code>.<br \/>\n    A binary tree can have a maximum of 2 children for each node, starting from the root node, and<br \/>\n    each node has a unique value.\n<\/p>\n<h3>Input Format<\/h3>\n<ul>\n<li>First line: Number of nodes <code>n<\/code> (1 \u2264 n \u2264 100,000)<\/li>\n<li>Second line: Tree structure (given parent nodes and child nodes)<\/li>\n<li>Third line: Two nodes <code>u<\/code>, <code>v<\/code><\/li>\n<\/ul>\n<h3>Output Format<\/h3>\n<p>\n    Output the lowest common ancestor of nodes <code>u<\/code> and <code>v<\/code>.\n<\/p>\n<h2>Example<\/h2>\n<pre>\nInput:\n7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n4 5\n\nOutput:\n2\n<\/pre>\n<h2>Approach to the Problem<\/h2>\n<p>\n    To solve this problem, we first need to construct the tree. The tree can be represented as an array or linked list, but<br \/>\n    using a linked list is more efficient. Then, we will record the depth of each node through DFS (Depth First Search) and<br \/>\n    store the parent nodes to easily find the LCA later.\n<\/p>\n<h2>Tree Construction<\/h2>\n<p>\n    Based on the given edge information, we will establish the parent-child relationships for the nodes.<br \/>\n    We will use Python&#8217;s dictionary to store the parent-child relationships.\n<\/p>\n<pre><code>\nfrom collections import defaultdict\n\ndef build_tree(edges):\n    tree = defaultdict(list)\n    for parent, child in edges:\n        tree[parent].append(child)\n    return tree\n<\/code><\/pre>\n<h2>Storing Depth and Parent Node Information via DFS<\/h2>\n<pre><code>\ndef dfs(tree, node, parent, depth, depths, parents):\n    depths[node] = depth\n    parents[node] = parent\n    for child in tree[node]:\n        if child != parent:\n            dfs(tree, child, node, depth + 1, depths, parents)\n<\/code><\/pre>\n<h2>Implementing the LCA Function<\/h2>\n<p>\n    After aligning the positions of the two nodes based on depth, we proceed upward along their parents until<br \/>\n    both nodes converge at the same node.\n<\/p>\n<pre><code>\ndef lca(u, v, depths, parents):\n    # Aligning Depths\n    if depths[u] < depths[v]:\n        u, v = v, u\n\n    while depths[u] > depths[v]:\n        u = parents[u]\n\n    while u != v:\n        u = parents[u]\n        v = parents[v]\n\n    return u\n<\/code><\/pre>\n<h2>Complete Code<\/h2>\n<pre><code>\ndef main():\n    n = int(input())\n    edges = [tuple(map(int, input().split())) for _ in range(n - 1)]\n    u, v = map(int, input().split())\n\n    tree = build_tree(edges)\n    depths = {}\n    parents = {}\n\n    # Collecting depth and parent information via DFS\n    dfs(tree, 1, -1, 0, depths, parents)\n\n    # Finding the lowest common ancestor\n    ancestor = lca(u, v, depths, parents)\n    print(ancestor)\n\nif __name__ == \"__main__\":\n    main()\n<\/code><\/pre>\n<h2>Time Complexity<\/h2>\n<p>\n    The time complexity of the above algorithm is O(n). This is because each node is visited once during the tree construction and traversal.\n<\/p>\n<h2>Conclusion<\/h2>\n<p>\n    The &#8216;Finding the Lowest Common Ancestor 2&#8217; problem is helpful for understanding the basics of searching and manipulating binary trees,<br \/>\n    and it is a practical algorithm. Through the process of solving this problem, one can gain a deep understanding of tree structures and the concept of DFS.<br \/>\n    This algorithm can be extended to various other problems and is also very useful in the application of other data structures.\n<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will explore one of the problems related to finding the &#8216;Lowest Common Ancestor (LCA)&#8217; called &#8216;Finding the Lowest Common Ancestor 2&#8217;. This problem involves finding the lowest common ancestor of two nodes in a specific tree structure, particularly in a binary tree. The LCA problem is a fundamental problem associated with &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33770\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Python Coding Test Course, Finding the Lowest Common Ancestor 2&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[145],"tags":[],"class_list":["post-33770","post","type-post","status-publish","format-standard","hentry","category-python-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/33770\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this article, we will explore one of the problems related to finding the &#8216;Lowest Common Ancestor (LCA)&#8217; called &#8216;Finding the Lowest Common Ancestor 2&#8217;. This problem involves finding the lowest common ancestor of two nodes in a specific tree structure, particularly in a binary tree. The LCA problem is a fundamental problem associated with &hellip; \ub354 \ubcf4\uae30 &quot;Python Coding Test Course, Finding the Lowest Common Ancestor 2&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33770\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:20:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:46:45+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"3\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Python Coding Test Course, Finding the Lowest Common Ancestor 2\",\"datePublished\":\"2024-11-01T09:20:11+00:00\",\"dateModified\":\"2024-11-01T11:46:45+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/\"},\"wordCount\":370,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Python Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33770\/\",\"name\":\"Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:20:11+00:00\",\"dateModified\":\"2024-11-01T11:46:45+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33770\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33770\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Coding Test Course, Finding the Lowest Common Ancestor 2\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/33770\/","og_locale":"ko_KR","og_type":"article","og_title":"Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this article, we will explore one of the problems related to finding the &#8216;Lowest Common Ancestor (LCA)&#8217; called &#8216;Finding the Lowest Common Ancestor 2&#8217;. This problem involves finding the lowest common ancestor of two nodes in a specific tree structure, particularly in a binary tree. The LCA problem is a fundamental problem associated with &hellip; \ub354 \ubcf4\uae30 \"Python Coding Test Course, Finding the Lowest Common Ancestor 2\"","og_url":"https:\/\/atmokpo.com\/w\/33770\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:20:11+00:00","article_modified_time":"2024-11-01T11:46:45+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"3\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/33770\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33770\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Python Coding Test Course, Finding the Lowest Common Ancestor 2","datePublished":"2024-11-01T09:20:11+00:00","dateModified":"2024-11-01T11:46:45+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33770\/"},"wordCount":370,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Python Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33770\/","url":"https:\/\/atmokpo.com\/w\/33770\/","name":"Python Coding Test Course, Finding the Lowest Common Ancestor 2 - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:20:11+00:00","dateModified":"2024-11-01T11:46:45+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33770\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33770\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33770\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Python Coding Test Course, Finding the Lowest Common Ancestor 2"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33770","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=33770"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33770\/revisions"}],"predecessor-version":[{"id":33771,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33770\/revisions\/33771"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33770"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33770"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33770"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}