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 C++ 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 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.
- Convert a given Binary tree to a tree that holds Logical AND property
- Convert a Binary Tree to a Circular Doubly Link List
- Minimum swap required to convert binary tree to binary search tree
- Convert Ternary Expression to a Binary Tree
- Print all k-sum paths in a binary tree
- HashSet vs TreeSet in Java
- Preorder from Inorder and Postorder traversals
- Count pairs in a binary tree whose sum is equal to a given value x
- Find the maximum node at a given level in a binary tree
- Print nodes in top view of Binary Tree | Set 2