Count levels in a Binary Tree consisting of node values having set bits at different positions | Structure of a node in the binary tree ; Function to find total unique levels ; Stores count of levels , where the set bits of all the nodes are at different positions ; Store nodes at each level of the tree using BFS ; Performing level order traversal ; Stores count of nodes at current level ; Stores prefix XOR of all the nodes at current level ; Stores prefix OR of all the nodes at current level ; Check if set bit of all the nodes at current level is at different positions or not ; Traverse nodes at current level ; Stores front element of the que ; Update prefix_OR ; Update prefix_XOR ; If left subtree not null ; If right subtree not null ; If bitwise AND is zero ; Driver Code ; Function Call
class TreeNode { constructor ( x ) { this . val = x ; this . left = null ; this . right = null ; } } function uniqueLevels ( root ) { let uniqueLevels = 0 ; let que = [ ] ; que . push ( root ) ; while ( que . length > 0 ) { let length = que . length ; let prefix_XOR = 0 ; let prefix_OR = 0 ; let flag = true ; for ( let i = 0 ; i < length ; i ++ ) { let temp = que [ 0 ] ; que . shift ( ) ; prefix_OR |= temp . val ; prefix_XOR ^= temp . val ; if ( prefix_XOR != prefix_OR ) flag = false ; if ( temp . left != null ) que . push ( temp . left ) ; if ( temp . right != null ) que . push ( temp . right ) ; } if ( flag ) uniqueLevels += 1 ; } document . write ( uniqueLevels ) ; } let root = new TreeNode ( 5 ) ; root . left = new TreeNode ( 6 ) ; root . right = new TreeNode ( 9 ) ; root . left . left = new TreeNode ( 1 ) ; root . left . right = new TreeNode ( 4 ) ; root . right . right = new TreeNode ( 7 ) ; uniqueLevels ( root ) ;