{"id":33492,"date":"2024-11-01T09:17:05","date_gmt":"2024-11-01T09:17:05","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33492"},"modified":"2024-11-01T11:38:23","modified_gmt":"2024-11-01T11:38:23","slug":"java-coding-test-course-lowest-common-ancestor","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33492\/","title":{"rendered":"Java Coding Test Course, Lowest Common Ancestor"},"content":{"rendered":"<p><body><\/p>\n<header>\n<p>In this article, we will take a detailed look at the definition and solutions of the Lowest Common Ancestor (LCA) problem.<\/p>\n<\/header>\n<section>\n<h2>Problem Definition<\/h2>\n<div class=\"problem\">\n<h3>Problem: Lowest Common Ancestor (LCA)<\/h3>\n<p>Find the lowest common ancestor of two nodes in a binary tree. The lowest common ancestor is the ancestor of both nodes and is the closest node to both nodes.<\/p>\n<p>For example, given the following binary tree:<\/p>\n<pre>\n                3\n              \/   \\\n             5     1\n            \/ \\   \/ \\\n           6   2 0   8\n              \/ \\\n             7   4\n        <\/pre>\n<p>The lowest common ancestor of node 5 and node 1 is 3, and the lowest common ancestor of node 5 and node 4 is 5.<\/p>\n<h4>Input Format<\/h4>\n<ul>\n<li>The root node of the binary tree and two nodes are given.<\/li>\n<\/ul>\n<h4>Output Format<\/h4>\n<ul>\n<li>Print the lowest common ancestor of the given two nodes.<\/li>\n<\/ul>\n<\/div>\n<\/section>\n<section>\n<h2>Problem Solution<\/h2>\n<h3>1. Problem Analysis<\/h3>\n<p>To find the lowest common ancestor of two nodes in the given binary tree, two conditions must be satisfied:<\/p>\n<ul>\n<li>There must exist a node B that is an ancestor of node A.<\/li>\n<li>There must also exist a node B that is an ancestor of node C.<\/li>\n<\/ul>\n<p>To establish this relationship, we can traverse the binary tree while tracking the parent node for each node.<\/p>\n<h3>2. Algorithm Design<\/h3>\n<p>First, to find a specific node in the binary tree, we can use search techniques such as DFS (Depth First Search) or BFS (Breadth First Search).<\/p>\n<p>The specific algorithm to find the lowest common ancestor is as follows:<\/p>\n<ol>\n<li>Start traversing the tree from the root node.<\/li>\n<li>Find the given two nodes in both subtrees.<\/li>\n<li>If one node is found in each subtree, the current node is the lowest common ancestor.<\/li>\n<li>If neither is found, return null.<\/li>\n<\/ol>\n<h3>3. Java Code Implementation<\/h3>\n<pre>\npublic class TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n\n    TreeNode(int x) {\n        val = x;\n    }\n}\n\npublic class LCA {\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        \/\/ Base case\n        if (root == null || root == p || root == q) {\n            return root;\n        }\n\n        \/\/ Find LCA in the left and right subtrees.\n        TreeNode left = lowestCommonAncestor(root.left, p, q);\n        TreeNode right = lowestCommonAncestor(root.right, p, q);\n\n        \/\/ If both are found, current node is the LCA.\n        if (left != null && right != null) {\n            return root;\n        }\n\n        \/\/ Return the result from the subtree where one was found.\n        return left != null ? left : right;\n    }\n}\n    <\/pre>\n<h3>4. Code Explanation<\/h3>\n<p>The key points in the above code are as follows:<\/p>\n<ul>\n<li>Recursively check if the current node is null or the node we are looking for.<\/li>\n<li>Find the lowest common ancestor in the left and right subtrees, and return the current node if both are found.<\/li>\n<li>Finally, if found only in one subtree, return that node; otherwise, return null.<\/li>\n<\/ul>\n<h3>5. Time Complexity<\/h3>\n<p>The time complexity of this algorithm is O(N), as each node in the collection is visited once. N is the number of nodes in the tree.<\/p>\n<h3>6. Space Complexity<\/h3>\n<p>The space complexity is O(H), where H is the height of the tree. In the worst case, if the binary tree is skewed to one side, the maximum height can be N.<\/p>\n<\/section>\n<section>\n<h2>Practical Code Test<\/h2>\n<p>To test the problem in practice, let&#8217;s create an example tree and write code to find the LCA.<\/p>\n<pre>\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Creating the binary tree\n        TreeNode root = new TreeNode(3);\n        TreeNode node5 = new TreeNode(5);\n        TreeNode node1 = new TreeNode(1);\n        TreeNode node6 = new TreeNode(6);\n        TreeNode node2 = new TreeNode(2);\n        TreeNode node0 = new TreeNode(0);\n        TreeNode node8 = new TreeNode(8);\n        TreeNode node7 = new TreeNode(7);\n        TreeNode node4 = new TreeNode(4);\n\n        root.left = node5;\n        root.right = node1;\n        node5.left = node6;\n        node5.right = node2;\n        node1.left = node0;\n        node1.right = node8;\n        node2.left = node7;\n        node2.right = node4;\n\n        \/\/ Create an object to find the LCA\n        LCA lcaFinder = new LCA();\n        TreeNode lca = lcaFinder.lowestCommonAncestor(root, node5, node1);\n        System.out.println(\"LCA of 5 and 1: \" + lca.val); \/\/ Output: 3\n\n        lca = lcaFinder.lowestCommonAncestor(root, node5, node4);\n        System.out.println(\"LCA of 5 and 4: \" + lca.val); \/\/ Output: 5\n    }\n}\n    <\/pre>\n<\/section>\n<section>\n<h2>Conclusion<\/h2>\n<p>In this article, we covered the problem of finding the lowest common ancestor in a binary tree, explaining the problem definition, algorithm design, Java code implementation, and code testing. This problem can be applied in various situations and is very helpful for understanding the basic concepts of algorithms and data structures.<\/p>\n<p>Through this, you can learn useful algorithm patterns for preparing for coding tests in Java and contribute to improving your problem-solving skills.<\/p>\n<\/section>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will take a detailed look at the definition and solutions of the Lowest Common Ancestor (LCA) problem. Problem Definition Problem: Lowest Common Ancestor (LCA) Find the lowest common ancestor of two nodes in a binary tree. The lowest common ancestor is the ancestor of both nodes and is the closest node &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33492\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Java Coding Test Course, Lowest Common Ancestor&#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":[139],"tags":[],"class_list":["post-33492","post","type-post","status-publish","format-standard","hentry","category-java-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Coding Test Course, Lowest Common Ancestor - \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\/33492\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this article, we will take a detailed look at the definition and solutions of the Lowest Common Ancestor (LCA) problem. Problem Definition Problem: Lowest Common Ancestor (LCA) Find the lowest common ancestor of two nodes in a binary tree. The lowest common ancestor is the ancestor of both nodes and is the closest node &hellip; \ub354 \ubcf4\uae30 &quot;Java Coding Test Course, Lowest Common Ancestor&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33492\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:17:05+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:38:23+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\/33492\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33492\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Java Coding Test Course, Lowest Common Ancestor\",\"datePublished\":\"2024-11-01T09:17:05+00:00\",\"dateModified\":\"2024-11-01T11:38:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33492\/\"},\"wordCount\":486,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Java Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33492\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33492\/\",\"name\":\"Java Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:17:05+00:00\",\"dateModified\":\"2024-11-01T11:38:23+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33492\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33492\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33492\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Coding Test Course, Lowest Common Ancestor\"}]},{\"@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":"Java Coding Test Course, Lowest Common Ancestor - \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\/33492\/","og_locale":"ko_KR","og_type":"article","og_title":"Java Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this article, we will take a detailed look at the definition and solutions of the Lowest Common Ancestor (LCA) problem. Problem Definition Problem: Lowest Common Ancestor (LCA) Find the lowest common ancestor of two nodes in a binary tree. The lowest common ancestor is the ancestor of both nodes and is the closest node &hellip; \ub354 \ubcf4\uae30 \"Java Coding Test Course, Lowest Common Ancestor\"","og_url":"https:\/\/atmokpo.com\/w\/33492\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:17:05+00:00","article_modified_time":"2024-11-01T11:38:23+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\/33492\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33492\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Java Coding Test Course, Lowest Common Ancestor","datePublished":"2024-11-01T09:17:05+00:00","dateModified":"2024-11-01T11:38:23+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33492\/"},"wordCount":486,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Java Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33492\/","url":"https:\/\/atmokpo.com\/w\/33492\/","name":"Java Coding Test Course, Lowest Common Ancestor - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:17:05+00:00","dateModified":"2024-11-01T11:38:23+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33492\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33492\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33492\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Java Coding Test Course, Lowest Common Ancestor"}]},{"@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\/33492","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=33492"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33492\/revisions"}],"predecessor-version":[{"id":33493,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33492\/revisions\/33493"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33492"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33492"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33492"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}