# Find the Kth node in the DFS traversal of a given subtree in a Tree in C++

C++Server Side ProgrammingProgramming

<p>In this problem, we are given a tree of size N, a node of the tree V and k. Our task is <em>find the Kth node in the DFS traversal of a given subtree in a Tree</em>.</p><p>We need to find the kth node in the DFS traversal of the tree starting from vertex V.</p><p><strong>Let&#39;s take an example to understand the problem,</strong></p><p>Input :</p><p><img src="https://www.tutorialspoint.com/assets/questions/media/60979/input.jpg" class="fr-fic fr-dib" width="373" height="399"></p><p>V = 2, k = 3</p><p>Output : 4</p><p><strong>Explanation</strong> &minus;</p><pre class="result notranslate">The series is {1, 2, 3, 5, 6, 7} The 4th element is 5.</pre><h2>Solution Approach</h2><p>A simple solution to the problem is find the DFS traversal of the node V and print the kth value from this.</p><p>For this, we perform DFS traversal of the tree and store it in a vector. In this vector, we will find values for V<sub>start</sub> and V<sub>end</sub> marking the start and end of the DFS traversal of the tree. Then find the k-th value in this range and print it if possible.</p><h2>Example</h2><p>Program to illustrate the working of our solution</p><pre class="just-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; #define N 100005 int n; vector&lt;int&gt; tree[N]; int currentIdx; vector&lt;int&gt; startIdx,endIdx; vector&lt;int&gt; dfsTraversalVector; void insertEdge(int u, int v){ &nbsp; &nbsp;tree[u].push_back(v); &nbsp; &nbsp;tree[v].push_back(u); } void findDfsTraversal(int ch, int par){ &nbsp; &nbsp;dfsTraversalVector[currentIdx] = ch; &nbsp; &nbsp;startIdx[ch] = currentIdx++; &nbsp; &nbsp;for (auto c : tree[ch]) { &nbsp; &nbsp; &nbsp; if (c != par) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;findDfsTraversal(c, ch); &nbsp; &nbsp;} &nbsp; &nbsp;endIdx[ch] = currentIdx - 1; } int findKNodeDfsV(int v, int k){ &nbsp; &nbsp;k = k + (startIdx[v] - 1); &nbsp; &nbsp;if (k &lt;= endIdx[v]) &nbsp; &nbsp; &nbsp; return dfsTraversalVector[k]; &nbsp; &nbsp;return -1; } int main(){ &nbsp; &nbsp;n = 9; &nbsp; &nbsp;insertEdge(5, 8); &nbsp; &nbsp;insertEdge(5, 2); &nbsp; &nbsp;insertEdge(5, 10); &nbsp; &nbsp;insertEdge(5, 3); &nbsp; &nbsp;insertEdge(2, 6); &nbsp; &nbsp;insertEdge(2, 1); &nbsp; &nbsp;insertEdge(3, 9); &nbsp; &nbsp;insertEdge(6, 1); &nbsp; &nbsp;insertEdge(9, 7); &nbsp; &nbsp;startIdx.resize(n); &nbsp; &nbsp;endIdx.resize(n); &nbsp; &nbsp;dfsTraversalVector.resize(n); &nbsp; &nbsp;findDfsTraversal(5, 0); &nbsp; &nbsp;int v = 2, &nbsp; &nbsp;k = 4; &nbsp; &nbsp;cout&lt;&lt;k&lt;&lt;&quot;-th node in DFS traversal of node &quot;&lt;&lt;v&lt;&lt;&quot; is &quot;&lt;&lt;findKNodeDfsV(v, k); &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">4-th node in DFS traversal of node 2 is 1</pre>