Check if all levels of two trees are anagrams or not | Iterative program to check if two trees are level by level anagram . ; A Binary Tree Node ; Returns true if trees with root1 and root2 are level by level anagram , else returns false . ; Base Cases ; start level order traversal of two trees using two queues . ; n1 ( queue size ) indicates number of Nodes at current level in first tree and n2 indicates number of nodes in current level of second tree . ; If n1 and n2 are different ; If level order traversal is over ; Dequeue all Nodes of current level and Enqueue all Nodes of next level ; Check if nodes of current levels are anagrams or not . ; Driver Code ; Constructing both the trees .
using System ; using System . Collections . Generic ; class GFG { public class Node { public Node left , right ; public int data ; public Node ( int data ) { this . data = data ; left = null ; right = null ; } } static Boolean areAnagrams ( Node root1 , Node root2 ) { if ( root1 == null && root2 == null ) return true ; if ( root1 == null root2 == null ) return false ; Queue < Node > q1 = new Queue < Node > ( ) ; Queue < Node > q2 = new Queue < Node > ( ) ; q1 . Enqueue ( root1 ) ; q2 . Enqueue ( root2 ) ; while ( true ) { int n1 = q1 . Count , n2 = q2 . Count ; if ( n1 != n2 ) return false ; if ( n1 == 0 ) break ; List < int > curr_level1 = new List < int > ( ) ; List < int > curr_level2 = new List < int > ( ) ; while ( n1 > 0 ) { Node node1 = q1 . Peek ( ) ; q1 . Dequeue ( ) ; if ( node1 . left != null ) q1 . Enqueue ( node1 . left ) ; if ( node1 . right != null ) q1 . Enqueue ( node1 . right ) ; n1 -- ; Node node2 = q2 . Peek ( ) ; q2 . Dequeue ( ) ; if ( node2 . left != null ) q2 . Enqueue ( node2 . left ) ; if ( node2 . right != null ) q2 . Enqueue ( node2 . right ) ; curr_level1 . Add ( node1 . data ) ; curr_level2 . Add ( node2 . data ) ; } curr_level1 . Sort ( ) ; curr_level2 . Sort ( ) ; for ( int i = 0 ; i < curr_level1 . Count ; i ++ ) if ( curr_level1 [ i ] != curr_level2 [ i ] ) return false ; } return true ; } public static void Main ( String [ ] args ) { Node root1 = new Node ( 1 ) ; root1 . left = new Node ( 3 ) ; root1 . right = new Node ( 2 ) ; root1 . right . left = new Node ( 5 ) ; root1 . right . right = new Node ( 4 ) ; Node root2 = new Node ( 1 ) ; root2 . left = new Node ( 2 ) ; root2 . right = new Node ( 3 ) ; root2 . left . left = new Node ( 4 ) ; root2 . left . right = new Node ( 5 ) ; Console . WriteLine ( areAnagrams ( root1 , root2 ) ? " Yes " : " No " ) ; } }