Given a rooted tree with N vertices and N-1 edges. We will be given many pairs of vertices u and v, we need to tell whether u is an ancestor of v or not. Given tree will be rooted at the vertex with index 0.
u = 1 v = 6 we can see from above tree that node 1 is ancestor of node 6 so the answer will be yes. u = 1 v = 7 we can see from above tree that node 1 is not an ancestor of node 7 so the answer will be no.
We can solve this problem using depth first search of the tree. While doing dfs we can observe a relation between the order in which we visit a node and its ancestors. If we assign in-time and out-time to each node when entering and leaving that node in dfs then we can see that for each pair of ancestor-descendant the in-time of ancestor is less than that of descendant and out-time of ancestor is more than that of descendant, so using this relation we can find the result for each pair of node in O(1) time.
So time complexity for preprocessing will be O(N) and for the query it will be O(1).
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Relationship between number of nodes and height of binary tree
- Segment Tree | Set 2 (Range Minimum Query)
- LCA for n-ary Tree | Constant Query O(1)
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Iterative Segment Tree (Range Minimum Query)
- Query to find the maximum and minimum weight between two nodes in the given tree using LCA.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Range query for Largest Sum Contiguous Subarray
- Range and Update Query for Chessboard Pieces
- Queries to search an element in an array and move it to front after every query
- Query to check if a range is made up of consecutive elements
- Convert a Binary Tree into its Mirror Tree
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if a binary tree is subtree of another binary tree | Set 1
- Convert a given tree to its Sum Tree
- Binary Tree to Binary Search Tree Conversion
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Improved By : sanjeev2552