Given a tree with N nodes, and two integers K and V. The task is to find the Kth node in the DFS traversal of the vertex V.
Consider the below Tree:
DFS of node number 1 is [1, 2, 3, 5, 6, 8, 7, 9, 4].
DFS of node number 3 is [3, 5, 6, 8, 7, 9]
DFS of node number 7 is [7, 9]
DFS of node number 9 is .
Print “-1” if the numbers in the DFS of vertex V are less than K.
Input : Tree: Shown in above image, V = 3, K = 4 Output : 8 Input : Tree: Shown in above image, V = 7, K = 3 Output : -1
Approach : Let’s construct a vector
So, to find the Kth node in the DFS of the subtree of node V, we will have to return the Kth node in the interval [tinv, toutv).
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Queries for M-th node in the DFS of subtree
- Subtree of all nodes in a tree using DFS
- Queries for DFS of a subtree in a tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find the kth node in vertical order traversal of a Binary Tree
- Kth ancestor of all nodes in an N-ary tree using DFS
- DFS traversal of a tree using recursion
- Construct the Rooted tree by using start and finish time of its DFS traversal
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Kth node in Diagonal Traversal of Binary Tree
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Print the DFS traversal step-wise (Backtracking also)
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.