Print alternate nodes from all levels of a Binary Tree | Java program to implement the above approach ; Structure of a Node ; Print alternate nodes of a binary tree ; Store nodes of each level ; Store count of nodes of current level ; Print alternate nodes of the current level ; If left child exists ; Store left child ; If right child exists ; Store right child ; Driver Code ; Create a tree
import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; Node ( int val ) { data = val ; left = right = null ; } } ; static void PrintAlternate ( Node root ) { Queue < Node > Q = new LinkedList < > ( ) ; Q . add ( root ) ; while ( ! Q . isEmpty ( ) ) { int N = Q . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Node temp = Q . peek ( ) ; Q . remove ( ) ; if ( i % 2 == 0 ) { System . out . print ( temp . data + " ▁ " ) ; } if ( temp . left != null ) { Q . add ( temp . left ) ; } if ( temp . right != null ) { Q . add ( temp . right ) ; } } System . out . println ( ) ; } } public static void main ( String [ ] args ) { Node root ; root = new Node ( 71 ) ; root . left = new Node ( 88 ) ; root . right = new Node ( 99 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . left . left . left = new Node ( 8 ) ; root . left . left . right = new Node ( 9 ) ; root . left . right . left = new Node ( 10 ) ; root . left . right . right = new Node ( 11 ) ; root . right . left . right = new Node ( 13 ) ; root . right . right . left = new Node ( 14 ) ; PrintAlternate ( root ) ; } }