Java Program to Partition a Tree from a Given Element using DFS
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array. DFS is a traversal method used to find the spanning tree out of a given graph or a tree.
To partition a tree from a given element means that we have to find different strongly connected trees generated by removing that element from the tree. So we will be using DFS to find different components of a partitioned tree which is formed after removing the given element. Hence, the DFS algorithm using java is a prerequisite.
Procedure: The partitioning of a tree from any element results in the following three cases:
Case 1: If that element has a parent and one left subtree and one right subtree, then there will be different spanning trees as follows:
- The first spanning tree will be that which is formed by doing DFS on the parent node of that particular element node.
- The second would result from the left subtree since all the nodes of a left subtree will get separated from the nodes of the parent and will result in a separate spanning tree.
- The third will be the right subtree as same as in the above case.
Case 2: If the node has only a parent node, then there will be only one partition (spanning tree) possible i.e. all nodes in that tree except that node.
Case 3: If the node has no parent and only child are present (root element), then if there are two children then two else one spanning tree is possible.
Case 4: If the node has only one child and a parent then two spanning trees are possible.
The following figure displays and clears all the cases.
Hence, we have to write a partition function that takes the input element and the adjacency list of the tree and then calls the DFS method after deciding the cases as stated above. Then the DFS function returns the spanning tree as generated by the partition. Hence, the Java Program is given below which partitions the tree from the given element.
1Tree 0 1 3 4 2Tree 5 7 8 3Tree 6 9
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.