![]() |
VOOZH | about |
Given n nodes of a tree and their connections, print Subtree nodes of every node.
Subtree of a node is defined as a tree which is a child of a node. The name emphasizes that everything which is a descendant of a tree node is a tree too, and is a subset of the larger tree.
Examples :
Input: N = 5 0 1 1 2 0 3 3 4 Output: Subtree of node 0 is 1 2 3 4 Subtree of node 1 is 2 Subtree of node 3 is 4 Input: N = 7 0 1 1 2 2 3 0 4 4 5 4 6 Output: Subtree of node 0 is 1 2 3 4 5 6 Subtree of node 1 is 2 3 Subtree of node 4 is 5 6
Approach: Do DFS traversal for every node and print all the nodes which are reachable from a particular node.
Explanation of below code:
Time Complexity: O(N ^ 2)
Auxiliary Space: O(N)