Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain forest of trees having even number of nodes. This problem is always solvable as given graph has even nodes.
Input : n = 10 Edge 1: 1 3 Edge 2: 1 6 Edge 3: 1 2 Edge 4: 3 4 Edge 5: 6 8 Edge 6: 2 7 Edge 7: 2 5 Edge 8: 4 9 Edge 9: 4 10 Output : 2 By removing 2 edges we can obtain the forest with even node tree. Dotted line shows removed edges. Any further removal of edge will not satisfy the even nodes condition.
Find a subtree with even number of nodes and remove it from rest of tree by removing the edge connecting it. After removal, we are left with tree with even node only because initially we have even number of nodes in the tree and removed subtree has also even node. Repeat the same procedure until we left with the tree that cannot be further decomposed in this manner.
To do this, the idea is to use Depth First Search to traverse the tree. Implement DFS function in such a manner that it will return number of nodes in the subtree whose root is node on which DFS is performed. If the number of nodes is even then remove the edge, else ignore.
Below is implementation of this approach:
Time Complexity: O(n).
This article is contributed by Anuj Chauhan. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Maximum edge removal from tree to make even forest
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Convert a given Binary tree to a tree that holds Logical AND property
- Convert a Binary Tree into its Mirror Tree
- Minimum swap required to convert binary tree to binary search tree
- Count number of trees in a forest
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Subtree of all nodes in a tree using DFS
- Sum of all nodes in a binary tree
- Convert Ternary Expression to a Binary Tree
- Convert left-right representation of a binary tree to down-right
- Convert a given tree to its Sum Tree
- Sum of all the Boundary Nodes of a Binary Tree
Improved By : PranchalK