<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ancestors Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/ancestors/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/ancestors/</link>
	<description></description>
	<lastBuildDate>Thu, 18 Jun 2020 23:17:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>ancestors Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/ancestors/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1483. Kth Ancestor of a Tree Node</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1483-kth-ancestor-of-a-tree-node/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1483-kth-ancestor-of-a-tree-node/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 16 Jun 2020 00:12:27 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[ancestors]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6940</guid>

					<description><![CDATA[<p>You are given a tree with&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n-1&#160;in the form of a parent array where&#160;parent[i]&#160;is the parent of node&#160;i. The root of the tree is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1483-kth-ancestor-of-a-tree-node/">花花酱 LeetCode 1483. Kth Ancestor of a Tree Node</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1483. Kth Ancestor of a Tree Node - 刷题找工作 EP336" width="500" height="375" src="https://www.youtube.com/embed/Vvk4xjLfk84?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a tree with&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n-1</code>&nbsp;in the form of a parent array where&nbsp;<code>parent[i]</code>&nbsp;is the parent of node&nbsp;<code>i</code>. The root of the tree is node&nbsp;<code>0</code>.</p>



<p>Implement the function&nbsp;<code>getKthAncestor</code><code>(int node, int k)</code>&nbsp;to return the&nbsp;<code>k</code>-th ancestor of the given&nbsp;<code>node</code>. If there is no such ancestor, return&nbsp;<code>-1</code>.</p>



<p>The&nbsp;<em>k-th&nbsp;</em><em>ancestor</em>&nbsp;of a tree node is the&nbsp;<code>k</code>-th node&nbsp;in the path&nbsp;from that node to the root.</p>



<p><strong>Example:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong>
["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"]
[[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]

<strong>Output:</strong>
</pre>


<p>[null,1,0,-1]</p>



<p><strong>Explanation:</strong>
TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);

treeAncestor.getKthAncestor(3, 1);  // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2);  // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3);  // returns -1 because there is no such ancestor
</p>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= k &lt;=&nbsp;n &lt;= 5*10^4</code></li><li><code>parent[0] == -1</code>&nbsp;indicating that&nbsp;<code>0</code>&nbsp;is the root node.</li><li><code>0 &lt;= parent[i] &lt; n</code>&nbsp;for all&nbsp;<code>0 &lt;&nbsp;i &lt; n</code></li><li><code>0 &lt;= node &lt; n</code></li><li>There will be at most&nbsp;<code>5*10^4</code>&nbsp;queries.</li></ul>



<h2><strong>Solution: LogN ancestors</strong> </h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-1.png" alt="" class="wp-image-6945" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-2.png" alt="" class="wp-image-6946" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-3.png" alt="" class="wp-image-6947" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1483-ep336-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<ol><li>Build the tree from parent array</li><li>Traverse the tree</li><li>For each node stores up to logn ancestros, 2^0-th, 2^1-th, 2^2-th, &#8230;</li></ol>



<p>When k comes in, each node take the highest bit h out, and query its 2^h&#8217;s ancestors with k &lt;- (k &#8211; 2^h). There will be at most logk recursive query. When it ends? k == 0, we found the ancestors which is the current node. Or node == 0 and k &gt; 0, we already at root which doesn&#8217;t have any ancestors so return -1.</p>



<p>Time complexity: <br>Construction: O(nlogn)<br>Query: O(logk)</p>



<p>Space complexity:<br>O(nlogn)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class TreeAncestor {
public:
  TreeAncestor(int n, vector&lt;int&gt;&amp; parent): 
    g_(n), a_(n) {
    for (int i = 1; i &lt; n; ++i) g_[parent[i]].push_back(i);
    vector&lt;int&gt; path;
    dfs(0, path);
  }

  int getKthAncestor(int node, int k) {
    if (k == 0) return node;
    if (node == 0 &amp;&amp; k &gt; 0) return -1;    
    int l = min(31ul - __builtin_clz(k), a_[node].size() - 1);
    return getKthAncestor(a_[node][l], k - (1 &lt;&lt; l));
  }
private:
  vector&lt;vector&lt;int&gt;&gt; g_, a_;  
  void dfs(int node, vector&lt;int&gt;&amp; path) {    
    for (int i = 1; i &lt;= path.size(); i *= 2)
      a_[node].push_back(path[path.size() - i]);
    path.push_back(node);
    for (int c : g_[node]) dfs(c, path);
    path.pop_back();    
  }
};</pre>
</div></div>



<p>DP method</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Author: Huahua
class TreeAncestor {
public:
  TreeAncestor(int n, vector&lt;int&gt;&amp; parent): 
    max_level_(32 - __builtin_clz(n)),
    dp_(max_level_, vector&lt;int&gt;(n)) {
    dp_[0] = parent;
    for (int i = 1; i &lt; max_level_; ++i)
      for (int j = 0; j &lt; n; ++j)
        dp_[i][j] = dp_[i - 1][j] == -1 ? -1 : dp_[i - 1][dp_[i - 1][j]];
  }

  int getKthAncestor(int node, int k) {    
    for (int i = 0; i &lt; max_level_ &amp;&amp; node != -1; ++i)
      if (k &amp; (1 &lt;&lt; i))
        node = dp_[i][node];
    return node;
  }
private:
  const int max_level_;
  vector&lt;vector&lt;int&gt;&gt; dp_;
};</pre>
</div></div>



<h2><strong>Solution 2: Binary Search</strong></h2>



<p>credit: Ziwu Zhou</p>



<p>Construction: O(n)</p>



<p>Traverse the tree in post order, for each node record its depth and id (visiting order).<br>For each depth, store all the nodes and their ids.</p>



<p>Query: O(logn)</p>



<p>Get the depth and id of the node, if k > d, return -1.<br>Use binary search to find the first node at depth[d &#8211; k] that has a id greater than the query&#8217;s one That node is the k-th ancestor of the node.</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class TreeAncestor {
public:
  TreeAncestor(int n, vector&lt;int&gt;&amp; parent):  g_(n), nodes_(n), levels_(n) {    
    for (int i = 1; i &lt; n; ++i)
      g_[parent[i]].push_back(i);
    int id = 0;
    dfs(0, 0, id);    
  }

  int getKthAncestor(int node, int k) {
    const auto [d, id] = nodes_[node];
    if (k &gt; d) return -1;
    const auto&amp; ns = levels_[d - k];
    return upper_bound(begin(ns), end(ns), pair{id, -1})-&gt;second;
  }
private:    
  void dfs(int node, int depth, int&amp; id) {
    for (int c : g_[node]) dfs(c, depth + 1, ++id);    
    levels_[depth].emplace_back(id, node);
    nodes_[node] = {depth, id};
  }  
  vector&lt;vector&lt;int&gt;&gt; g_; // p -&gt; {{child}}
  vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; levels_; // depth -&gt; {{id, node}}
  vector&lt;pair&lt;int, int&gt;&gt; nodes_; // node -&gt; {depth, id}
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1483-kth-ancestor-of-a-tree-node/">花花酱 LeetCode 1483. Kth Ancestor of a Tree Node</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-1483-kth-ancestor-of-a-tree-node/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
