{"id":33812,"date":"2024-11-01T09:20:42","date_gmt":"2024-11-01T09:20:42","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33812"},"modified":"2024-11-01T11:46:34","modified_gmt":"2024-11-01T11:46:34","slug":"python-coding-test-course-finding-the-diameter-of-a-tree","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33812\/","title":{"rendered":"Python Coding Test Course, Finding the Diameter of a Tree"},"content":{"rendered":"<p><body><\/p>\n<p>\n        Trees are one of the most important data structures in computer science. In particular, trees are useful for representing hierarchical relationships and are used in various algorithmic problems. This lecture will cover the problem of finding the diameter of a tree.<br \/>\n        The diameter refers to the longest path between two nodes in the tree. This problem can be solved using DFS (Depth First Search) or BFS (Breadth First Search) algorithms.\n    <\/p>\n<h2>Problem Description<\/h2>\n<p>\n        Each node in the given non-empty tree is represented by an integer. Solve the problem of finding the length of the longest path between two nodes in the tree.<br \/>\n        The input consists of the number of nodes in the tree <code>N<\/code> and <code>N-1<\/code> edge information. The edge information is provided in a way that connects two nodes.<br \/>\n        Specifically, the input will be given in the following format:\n    <\/p>\n<pre>\n    N\n    a1 b1\n    a2 b2\n    ...\n    a(N-1) b(N-1)\n    <\/pre>\n<p>\n        Here, <code>a<\/code> and <code>b<\/code> represent the two connected nodes, respectively.\n    <\/p>\n<h2>Input Example<\/h2>\n<pre>\n    5\n    1 2\n    1 3\n    2 4\n    2 5\n    <\/pre>\n<h2>Output Example<\/h2>\n<pre>\n    3\n    <\/pre>\n<p>\n        In this case, the diameter of the tree is between node 4 and node 5, with the path being 4 \u2192 2 \u2192 1 \u2192 3 or 4 \u2192 2 \u2192 5.<br \/>\n        Therefore, the output is <code>3<\/code>.\n    <\/p>\n<h2>Solution<\/h2>\n<p>\n        To find the diameter of the tree, we can use DFS or BFS algorithms.<br \/>\n        The general approach is as follows:\n    <\/p>\n<ol>\n<li>\n            In the first step, perform DFS from an arbitrary node to find the farthest node.<br \/>\n            Let&#8217;s call this node <code>X<\/code>.\n        <\/li>\n<li>\n            In the second step, perform DFS again from node <code>X<\/code> to find the farthest node, <code>Y<\/code>.<br \/>\n            The path between <code>X<\/code> and <code>Y<\/code> will be the diameter of the tree.\n        <\/li>\n<\/ol>\n<p>\n        Through this process, the time complexity will be <code>O(N)<\/code>, implemented by recursively calling DFS.\n    <\/p>\n<h2>Python Code Implementation<\/h2>\n<p>\n        Now, based on the logic above, let&#8217;s implement the code to find the diameter of the tree in Python.<br \/>\n        Check the details of each step with the code provided below.\n    <\/p>\n<pre>\n<code>from collections import defaultdict\n\ndef dfs(graph, node, visited):\n    visited.add(node)\n    max_distance = 0\n    farthest_node = node\n\n    for neighbor in graph[node]:\n        if neighbor not in visited:\n            distance, next_node = dfs(graph, neighbor, visited)\n            distance += 1\n            \n            if distance &gt; max_distance:\n                max_distance = distance\n                farthest_node = next_node\n\n    return max_distance, farthest_node\n\ndef tree_diameter(edges, n):\n    graph = defaultdict(list)\n    \n    for a, b in edges:\n        graph[a].append(b)\n        graph[b].append(a)\n\n    # Step 1: start DFS from an arbitrary node (1)\n    visited = set()\n    _, farthest_node = dfs(graph, 1, visited)\n\n    # Step 2: start DFS from the farthest node found\n    visited.clear()\n    diameter, _ = dfs(graph, farthest_node, visited)\n\n    return diameter\n\n# Input reading part\nn = int(input())\nedges = [tuple(map(int, input().split())) for _ in range(n-1)]\nprint(tree_diameter(edges, n))\n<\/code>\n    <\/pre>\n<h2>Code Explanation<\/h2>\n<p>\n        The above code is structured in the following way:\n    <\/p>\n<ul>\n<li>\n<code>collections.defaultdict<\/code> is used to create the graph in the form of an adjacency list.<br \/>\n            This represents the connectivity between nodes.\n        <\/li>\n<li>\n<code>dfs<\/code> function performs depth-first search and calculates the distance to each node.<br \/>\n            It returns the farthest node and distance.\n        <\/li>\n<li>\n<code>tree_diameter<\/code> function coordinates the overall process and calculates the diameter through two DFS calls.\n        <\/li>\n<li>\n            In the last part, it takes input from the user and calls the <code>tree_diameter<\/code> function to output the result.\n        <\/li>\n<\/ul>\n<h2>Performance Analysis<\/h2>\n<p>\n        The presented algorithm has a time complexity of <code>O(N)<\/code>.<br \/>\n        This is possible because it visits all nodes in the tree once through DFS.<br \/>\n        Therefore, it can efficiently calculate the diameter even for very large trees.\n    <\/p>\n<h2>Conclusion<\/h2>\n<p>\n        In this lecture, we explored the diameter of trees.<br \/>\n        We were able to efficiently solve the problem using a DFS approach.<br \/>\n        Trees are utilized in various problems, so it is beneficial to thoroughly understand the contents of this lecture.<br \/>\n        If you have additional questions or need practice problems, please leave a comment.\n    <\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Trees are one of the most important data structures in computer science. In particular, trees are useful for representing hierarchical relationships and are used in various algorithmic problems. This lecture will cover the problem of finding the diameter of a tree. The diameter refers to the longest path between two nodes in the tree. This &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33812\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Python Coding Test Course, Finding the Diameter of a Tree&#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-33812","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 Diameter of a Tree - \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\/33812\/\" \/>\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 Diameter of a Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Trees are one of the most important data structures in computer science. In particular, trees are useful for representing hierarchical relationships and are used in various algorithmic problems. This lecture will cover the problem of finding the diameter of a tree. The diameter refers to the longest path between two nodes in the tree. This &hellip; \ub354 \ubcf4\uae30 &quot;Python Coding Test Course, Finding the Diameter of a Tree&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33812\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:20:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:46:34+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\/33812\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33812\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Python Coding Test Course, Finding the Diameter of a Tree\",\"datePublished\":\"2024-11-01T09:20:42+00:00\",\"dateModified\":\"2024-11-01T11:46:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33812\/\"},\"wordCount\":462,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Python Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33812\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33812\/\",\"name\":\"Python Coding Test Course, Finding the Diameter of a Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:20:42+00:00\",\"dateModified\":\"2024-11-01T11:46:34+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33812\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33812\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33812\/#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 Diameter of a Tree\"}]},{\"@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 Diameter of a Tree - \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\/33812\/","og_locale":"ko_KR","og_type":"article","og_title":"Python Coding Test Course, Finding the Diameter of a Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Trees are one of the most important data structures in computer science. In particular, trees are useful for representing hierarchical relationships and are used in various algorithmic problems. This lecture will cover the problem of finding the diameter of a tree. The diameter refers to the longest path between two nodes in the tree. This &hellip; \ub354 \ubcf4\uae30 \"Python Coding Test Course, Finding the Diameter of a Tree\"","og_url":"https:\/\/atmokpo.com\/w\/33812\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:20:42+00:00","article_modified_time":"2024-11-01T11:46:34+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\/33812\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33812\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Python Coding Test Course, Finding the Diameter of a Tree","datePublished":"2024-11-01T09:20:42+00:00","dateModified":"2024-11-01T11:46:34+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33812\/"},"wordCount":462,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Python Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33812\/","url":"https:\/\/atmokpo.com\/w\/33812\/","name":"Python Coding Test Course, Finding the Diameter of a Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:20:42+00:00","dateModified":"2024-11-01T11:46:34+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33812\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33812\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33812\/#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 Diameter of a Tree"}]},{"@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\/33812","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=33812"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33812\/revisions"}],"predecessor-version":[{"id":33813,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33812\/revisions\/33813"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33812"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33812"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33812"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}