Given an n-ary tree of n vertices and n-1 edges. The tree is given in the form of adjacency list. Find number of subtrees of even size in given tree.
Input : 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 Output : 2 Subtree rooted at 1 and 3 are of even size. Input : 1 / \ 2 3 / | \ \ 4 5 6 7 / | \ 8 9 10 Output : 3 Subtree rooted at 1, 3 and 5 are of even size.
A simple solution is to perform dfs starting from every node and find size of subtree rooted at that node. If size is even increment count. Time complexity of above solution is O(n2).
A better solution is to perform single dfs on given tree. The idea is to first find recursively size of subtree of all childeren nodes, then find size of subtree rooted at current node by taking sum of size of children node subtrees and increment count if size is even.
Below is the implementation of above approach:
Time Complexity: O(n)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find the largest BST subtree in a given Binary Tree | Set 1
- Subtree with given sum in a Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Subtree of all nodes in a tree using DFS
- Euler Tour | Subtree Sum using Segment Tree
- Find largest subtree sum in a tree
- Find the largest Complete Subtree in a given Binary Tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Queries for DFS of a subtree in a tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Duplicate subtree in Binary Tree | SET 2
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Print even positioned nodes of even levels in level order of the given binary tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.