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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.