{"id":2972,"date":"2018-06-30T23:12:53","date_gmt":"2018-07-01T06:12:53","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=2972"},"modified":"2018-07-01T17:56:13","modified_gmt":"2018-07-02T00:56:13","slug":"leetcode-863-all-nodes-distance-k-in-binary-tree","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/searching\/leetcode-863-all-nodes-distance-k-in-binary-tree\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 863. All Nodes Distance K in Binary Tree"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 863. All Nodes Distance K in Binary Tree - \u5237\u9898\u627e\u5de5\u4f5c EP202\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/o1siL8eKCos?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<h1>Problem<\/h1>\n<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u68f5\u4e8c\u53c9\u6811\uff08\u6839\u7ed3\u70b9root\uff09\u548c\u4e00\u4e2atarget\u8282\u70b9\u3002\u8fd4\u56de\u6240\u6709\u5230target\u7684\u8ddd\u79bb\u4e3aK\u7684\u8282\u70b9\u3002<\/p>\n<p>We are given a binary tree (with root node\u00a0<code>root<\/code>), a\u00a0<code>target<\/code>\u00a0node, and an integer value `<span style=\"font-family: monospace;\">K`<\/span>.<\/p>\n<p>Return a list of the values of all\u00a0nodes that have a distance\u00a0<code>K<\/code>\u00a0from the\u00a0<code>target<\/code>\u00a0node.\u00a0 The answer can be returned in any order.<\/p>\n<p><strong>Example 1:<\/strong><\/p>\n<pre class=\"crayon:false\"><strong>Input: <\/strong>root = <span id=\"example-input-1-1\">[3,5,1,6,2,0,8,null,null,7,4]<\/span>, target = <span id=\"example-input-1-2\">5<\/span>, K = <span id=\"example-input-1-3\">2<\/span>\r\n<strong>Output: <\/strong><span id=\"example-output-1\">[7,4,1]<\/span>\r\n<strong>Explanation: <\/strong>\r\nThe nodes that are a distance 2 from the target node (with value 5)\r\nhave values 7, 4, and 1.\r\n<img decoding=\"async\" src=\"https:\/\/s3-lc-upload.s3.amazonaws.com\/uploads\/2018\/06\/28\/sketch0.png\" alt=\"\" \/>\r\nNote that the inputs \"root\" and \"target\" are actually TreeNodes.\r\nThe descriptions of the inputs above are just serializations of these objects.\r\n\r\n<\/pre>\n<p><strong>Note:<\/strong><\/p>\n<ol>\n<li>The given tree is non-empty.<\/li>\n<li>Each node in the tree has unique values\u00a0<code>0 &lt;= node.val &lt;= 500<\/code>.<\/li>\n<li>The\u00a0<code>target<\/code>\u00a0node is a node in the tree.<\/li>\n<li><code>0 &lt;= K &lt;= 1000<\/code>.<\/li>\n<\/ol>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2983\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/06\/863-ep202.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/06\/863-ep202.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/06\/863-ep202-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/06\/863-ep202-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<h1><strong>Solution1: DFS + BFS<\/strong><\/h1>\n<p>Use DFS to build the graph, and use BFS to find all the nodes that are exact K steps from target.<\/p>\n<p>Time complexity: O(n)<\/p>\n<p>Space complexity: O(n)<\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 6 ms\r\nclass Solution {\r\npublic:\r\n  vector&lt;int&gt; distanceK(TreeNode* root, TreeNode* target, int K) {\r\n    buildGraph(nullptr, root);    \r\n    vector&lt;int&gt; ans;\r\n    unordered_set&lt;TreeNode*&gt; seen;    \r\n    queue&lt;TreeNode*&gt; q;\r\n    seen.insert(target);\r\n    q.push(target);\r\n    int k = 0;\r\n    while (!q.empty() &amp;&amp; k &lt;= K) {\r\n      int s = q.size();\r\n      while (s--) {\r\n        TreeNode* node = q.front(); q.pop();\r\n        if (k == K) ans.push_back(node-&gt;val);    \r\n        for (TreeNode* child : g[node]) {\r\n          if (seen.count(child)) continue;\r\n          q.push(child);\r\n          seen.insert(child);\r\n        }\r\n      }\r\n      ++k;\r\n    }\r\n    return ans;\r\n  }\r\nprivate:  \r\n  unordered_map&lt;TreeNode*, vector&lt;TreeNode*&gt;&gt; g;\r\n  \r\n  void buildGraph(TreeNode* parent, TreeNode* child) {      \r\n    if (parent) {\r\n      g[parent].push_back(child);\r\n      g[child].push_back(parent);\r\n    }\r\n    if (child-&gt;left) buildGraph(child, child-&gt;left);\r\n    if (child-&gt;right) buildGraph(child, child-&gt;right);\r\n  }\r\n};<\/pre>\n<p>Array version<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 6 ms\r\nclass Solution {\r\npublic:\r\n  vector&lt;int&gt; distanceK(TreeNode* root, TreeNode* target, int K) {\r\n    constexpr int kMaxN = 500 + 1;\r\n    g = vector&lt;vector&lt;int&gt;&gt;(kMaxN);\r\n    buildGraph(nullptr, root);\r\n    vector&lt;int&gt; ans;\r\n    vector&lt;int&gt; seen(kMaxN);    \r\n    queue&lt;int&gt; q;\r\n    seen[target-&gt;val] = 1;\r\n    q.push(target-&gt;val);\r\n    int k = 0;\r\n    while (!q.empty() &amp;&amp; k &lt;= K) {\r\n      int s = q.size();\r\n      while (s--) {\r\n        int node = q.front(); q.pop();\r\n        if (k == K) ans.push_back(node);\r\n        for (int child : g[node]) {\r\n          if (seen[child]) continue;\r\n          q.push(child);\r\n          seen[child] = 1;\r\n        }\r\n      }\r\n      ++k;\r\n    }\r\n    return ans;\r\n  }\r\nprivate:  \r\n  vector&lt;vector&lt;int&gt;&gt; g;\r\n  \r\n  void buildGraph(TreeNode* parent, TreeNode* child) {      \r\n    if (parent) {\r\n      g[parent-&gt;val].push_back(child-&gt;val);\r\n      g[child-&gt;val].push_back(parent-&gt;val);\r\n    }\r\n    if (child-&gt;left) buildGraph(child, child-&gt;left);\r\n    if (child-&gt;right) buildGraph(child, child-&gt;right);\r\n  }\r\n};<\/pre>\n<h1><strong>Solution 2: Recursion<\/strong><\/h1>\n<p>Recursively compute the distance from root to target, and collect nodes accordingly.<\/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\/\/ Running time: 5 ms\r\nclass Solution {\r\npublic:\r\n  vector&lt;int&gt; distanceK(TreeNode* root, TreeNode* target, int K) {\r\n    ans.clear();\r\n    dis(root, target, K);\r\n    return ans;\r\n  }\r\nprivate:\r\n  vector&lt;int&gt; ans;\r\n  \/\/ Returns the distance from root to target.\r\n  \/\/ Returns -1 if target does not in the tree.\r\n  int dis(TreeNode* root, TreeNode* target, int K) {\r\n    if (root == nullptr) return -1;\r\n    if (root == target) {\r\n      collect(target, K);\r\n      return 0;\r\n    }\r\n    \r\n    int l = dis(root-&gt;left, target, K);\r\n    int r = dis(root-&gt;right, target, K);\r\n    \r\n    \/\/ Target in the left subtree\r\n    if (l &gt;= 0) {\r\n      if (l == K - 1) ans.push_back(root-&gt;val);\r\n      \/\/ Collect nodes in right subtree with depth K - l - 2\r\n      collect(root-&gt;right, K - l - 2);\r\n      return l + 1;\r\n    }\r\n    \r\n    \/\/ Target in the right subtree\r\n    if (r &gt;= 0) {\r\n      if (r == K - 1) ans.push_back(root-&gt;val);\r\n      \/\/ Collect nodes in left subtree with depth K - r - 2\r\n      collect(root-&gt;left, K - r - 2);\r\n      return r + 1;\r\n    }\r\n    \r\n    return -1;\r\n  }\r\n  \r\n  \/\/ Collect nodes that are d steps from root.\r\n  void collect(TreeNode* root, int d) {\r\n    if (root == nullptr || d &lt; 0) return;\r\n    if (d == 0) ans.push_back(root-&gt;val);\r\n    collect(root-&gt;left, d - 1);\r\n    collect(root-&gt;right, d - 1);\r\n  }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem \u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u68f5\u4e8c\u53c9\u6811\uff08\u6839\u7ed3\u70b9root\uff09\u548c\u4e00\u4e2atarget\u8282\u70b9\u3002\u8fd4\u56de\u6240\u6709\u5230target\u7684\u8ddd\u79bb\u4e3aK\u7684\u8282\u70b9\u3002 We are given a binary tree (with root node\u00a0root), a\u00a0target\u00a0node, and an integer value `K`. Return a list of the values of all\u00a0nodes&#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,44,45],"tags":[34,33,77,42,28],"class_list":["post-2972","post","type-post","status-publish","format-standard","hentry","category-graph","category-searching","category-tree","tag-bfs","tag-dfs","tag-graph","tag-search","tag-tree","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/2972","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=2972"}],"version-history":[{"count":8,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/2972\/revisions"}],"predecessor-version":[{"id":2985,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/2972\/revisions\/2985"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=2972"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=2972"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=2972"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}