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 : to store the DFS traversal of the complete tree from vertex 1. Let tinv be the position of the vertex V in the vector p (the size of the vector p in moment we call DFS from the vertex V) and toutv be the position of the first vertex pushed to the vector after leaving the subtree of vertex V (the size of the vector p in moment when we return from DFS from the vertex V). Then it is obvious that the subtree of the vertex V lies in the interval [tinv, toutv).
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:
- Find n-th node in Preorder traversal of a Binary Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Find the kth node in vertical order traversal of a Binary Tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find largest subtree sum in a tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Perfect Subtree in a given Binary Tree
- Find the largest Complete Subtree in a given Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Print cousins of a given node in Binary Tree | Single Traversal
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Create a binary tree from post order traversal and leaf node array
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.
Improved By : mohit kumar 29