Given two binary trees, we have to check if each of their levels are anagrams of each other or not.
Tree 1: Level 0 : 1 Level 1 : 3, 2 Level 2 : 5, 4 Tree 2: Level 0 : 1 Level 1 : 2, 3 Level 2 : 4, 5
As we can clearly see all the levels of above two binary trees are anagrams of each other, hence return true.
Naive Approach: Below is the step by step explanation of the naive approach to do this:
- Write a recursive program for level order traversal of a tree.
- Traverse each level of both the trees one by one and store the result of traversals in 2 different vectors, one for each tree.
- Sort both the vectors and compare them iteratively for each level, if they are same for each level then return true else return false.
Time Complexity: O(n^2), where n is the number of nodes.
The idea is based on below article.
Print level order traversal line by line | Set 1
We traverse both trees simultaneously level by level. We store each level both trees in vectors (or array). To check if two vectors are anagram or not, we sort both and then compare.
Time Complexity: O(n), where n is the number of nodes.
Note: In the above program we are comparing the vectors storing each level of a tree directly using not equal to function ‘ != ‘ which compares the vectors first on the basis of their size and then on the basis of their content, hence saving our work of iteratively comparing the vectors.
This article is contributed by Aditya Gupta. 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.
- Check if two strings are k-anagrams or not
- Check whether two strings are anagrams of each other using unordered_map in C++
- Check given array of size n can represent BST of n levels or not
- Check if two trees are Mirror
- Check if two trees have same structure
- Check if two trees are Mirror | Set 2
- Iterative method to check if two trees are mirror of each other
- Iterative function to check if two trees are identical
- Check if leaf traversal of two Binary Trees is same?
- Check if two trees are mirror of each other using level order traversal
- Count Occurences of Anagrams
- Given a sequence of words, print all anagrams together using STL
- Number of index pairs such that s[i] and s[j] are anagrams
- Project Idea | (A Game of Anagrams )
- Given a sequence of words, print all anagrams together | Set 1