VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sub-tree-nodes-tree-using-dfs/

⇱ Subtree of all nodes in a tree using DFS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subtree of all nodes in a tree using DFS

Last Updated : 3 Nov, 2022

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.
 

👁 Image


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: 
 

  1. When function dfs(0, 0) is called, start[0] = 0, dfs_order.push_back(0), visited[0] = 1 to keep track of dfs order.
  2. Now, consider adjacency list (adj[100001]) as considering directional path elements connected to node 0 will be in adjacency list corresponding to node 0.
  3. Now, recursively call dfs function till all elements traversed of adj[0].
  4. Now, dfs(1, 2) is called, Now start[1] = 1, dfs_order.push_back(1), visited[1] = 1 after adj[1] elements is traversed.
  5. Now adj [1] is traversed which contain only node 2 when adj[2] is traversed it contains no element, it will break and end[1]=2.
  6. Similarly, all nodes traversed and store dfs_order in array to find subtree of nodes.


 


Time Complexity: O(N ^ 2)
Auxiliary Space: O(N)

Comment
Article Tags: