Count levels in a Binary Tree consisting of node values having set bits at different positions | Java program for the above approach ; 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
import java . util . * ; class GFG { static class TreeNode { int val = 0 ; TreeNode left , right ; TreeNode ( int x ) { val = x ; left = null ; right = null ; } } ; static void uniqueLevels ( TreeNode root ) { int uniqueLevels = 0 ; Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( que . size ( ) > 0 ) { int length = que . size ( ) ; int prefix_XOR = 0 ; int prefix_OR = 0 ; boolean flag = true ; for ( int i = 0 ; i < length ; i ++ ) { TreeNode temp = que . peek ( ) ; que . remove ( ) ; prefix_OR |= temp . val ; prefix_XOR ^= temp . val ; if ( prefix_XOR != prefix_OR ) flag = false ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; } if ( flag ) uniqueLevels += 1 ; } System . out . print ( uniqueLevels ) ; } public static void main ( String [ ] args ) { TreeNode 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 ) ; } }