{"id":1216,"date":"2017-12-12T22:21:27","date_gmt":"2017-12-13T06:21:27","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1216"},"modified":"2018-04-19T08:28:28","modified_gmt":"2018-04-19T15:28:28","slug":"742-closest-leaf-in-a-binary-tree","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/742-closest-leaf-in-a-binary-tree\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 742. Closest Leaf in a Binary Tree"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 742. Closest Leaf in a Binary Tree - \u5237\u9898\u627e\u5de5\u4f5c EP131\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/x1wXkRrpavw?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Given a binary tree\u00a0<b>where every node has a unique value<\/b>, and a target key\u00a0<code>k<\/code>, find the value of the closest leaf node to target\u00a0<code>k<\/code>\u00a0in the tree.<\/p>\n<p>Here,\u00a0<i>closest<\/i>\u00a0to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called a\u00a0<i>leaf<\/i>\u00a0if it has no children.<\/p>\n<p>In the following examples, the input tree is represented in flattened form row by row. The actual\u00a0<code>root<\/code>\u00a0tree given will be a TreeNode object.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"theme:classic toolbar:2 lang:default highlight:0 decode:true\">Input:\r\nroot = [1, 3, 2], k = 1\r\nDiagram of binary tree:\r\n          1\r\n         \/ \\\r\n        3   2\r\n\r\nOutput: 2 (or 3)\r\n\r\nExplanation: Either 2 or 3 is the closest leaf node to the target of 1.\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"theme:classic toolbar:2 lang:default highlight:0 decode:true\">Input:\r\nroot = [1], k = 1\r\nOutput: 1\r\n\r\nExplanation: The closest leaf node is the root node itself.\r\n<\/pre>\n<p><b>Example 3:<\/b><\/p>\n<pre class=\"theme:classic toolbar:2 lang:default highlight:0 decode:true\">Input:\r\nroot = [1,2,3,4,null,null,null,5,null,6], k = 2\r\nDiagram of binary tree:\r\n             1\r\n            \/ \\\r\n           2   3\r\n          \/\r\n         4\r\n        \/\r\n       5\r\n      \/\r\n     6\r\n\r\nOutput: 3\r\nExplanation: The leaf node with value 3 (and not the leaf node with value 6) is closest to the node with value 2.\r\n<\/pre>\n<p><b>Note:<\/b><\/p>\n<ol>\n<li><code>root<\/code>\u00a0represents a binary tree with at least\u00a0<code>1<\/code>\u00a0node and at most\u00a0<code>1000<\/code>\u00a0nodes.<\/li>\n<li>Every node has a unique\u00a0<code>node.val<\/code>\u00a0in range\u00a0<code>[1, 1000]<\/code>.<\/li>\n<li>There exists some node in the given binary tree for which\u00a0<code>node.val == k<\/code>.<\/li>\n<\/ol>\n<p><ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>\u9898\u76ee\u5927\u610f:<\/strong><\/p>\n<p>\u7ed9\u4f60\u4e00\u68f5\u6811\uff0c\u6bcf\u4e2a\u8282\u70b9\u7684\u503c\u90fd\u4e0d\u76f8\u540c\u3002<\/p>\n<p>\u7ed9\u5b9a\u4e00\u4e2a\u8282\u70b9\u503c\uff0c\u8ba9\u4f60\u627e\u5230\u79bb\u8fd9\u4e2a\u8282\u70b9\u8ddd\u79bb\u6700\u8fd1\u7684\u53f6\u5b50\u8282\u70b9\u7684\u503c\u3002<\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>Shortest path from source to any leaf nodes in a undirected unweighted graph.<\/p>\n<p>\u95ee\u9898\u8f6c\u6362\u4e3a\u5728\u65e0\u5411\/\u7b49\u6743\u91cd\u7684\u56fe\u4e2d\u627e\u4e00\u6761\u4ece\u8d77\u59cb\u8282\u70b9\u5230\u4efb\u610f\u53f6\u5b50\u8282\u70b9\u6700\u77ed\u8def\u5f84\u3002<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1222\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/742-ep131.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/742-ep131.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/742-ep131-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/742-ep131-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<p><strong>Solution:<\/strong><\/p>\n<p>C++ \/ DFS + BFS<\/p>\n<p>Time complexity: O(n)<\/p>\n<p>Space complexity: O(n)<\/p>\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 16 ms\r\nclass Solution {\r\npublic:\r\n    int findClosestLeaf(TreeNode* root, int k) {\r\n        graph_.clear();\r\n        start_ = nullptr;\r\n        buildGraph(root, nullptr, k);\r\n        queue&lt;TreeNode*&gt; q;\r\n        q.push(start_);\r\n        unordered_set&lt;TreeNode*&gt; seen;\r\n        while (!q.empty()) {\r\n            int size = q.size();\r\n            while (size--&gt;0) {\r\n                TreeNode* curr = q.front();\r\n                q.pop();                \r\n                seen.insert(curr);                \r\n                if (!curr-&gt;left &amp;&amp; !curr-&gt;right) return curr-&gt;val;\r\n                for (TreeNode* node : graph_[curr])\r\n                    if (!seen.count(node)) q.push(node);\r\n            }\r\n        }\r\n        return 0;\r\n    }\r\nprivate:\r\n    void buildGraph(TreeNode* node, TreeNode* parent, int k) {\r\n        if (!node) return;\r\n        if (node-&gt;val == k) start_ = node;\r\n        if (parent) {\r\n            graph_[node].push_back(parent);\r\n            graph_[parent].push_back(node);\r\n        }\r\n        buildGraph(node-&gt;left, node, k);\r\n        buildGraph(node-&gt;right, node, k);\r\n    }\r\n    \r\n    unordered_map&lt;TreeNode*, vector&lt;TreeNode*&gt;&gt; graph_;\r\n    TreeNode* start_;\r\n};<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a binary tree\u00a0where every node has a unique value, and a target key\u00a0k, find the value of the closest leaf node to target\u00a0k\u00a0in&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76,164,45],"tags":[34,33,177,87],"class_list":["post-1216","post","type-post","status-publish","format-standard","hentry","category-graph","category-medium","category-tree","tag-bfs","tag-dfs","tag-medium","tag-shortest-path","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1216"}],"version-history":[{"count":8,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1216\/revisions"}],"predecessor-version":[{"id":1235,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1216\/revisions\/1235"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}