Iterative diagonal traversal of binary tree | Java program to con string from binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; Iterative function to print diagonal view ; base case ; inbuilt queue of Treenode ; add root ; add delimiter ; if current is delimiter then insert another for next diagonal and cout nextline ; if queue is empty return ; output nextline ; add delimiter again ; if left child is present add into queue ; current equals to right child ; Driver Code
import java . util . * ; class solution { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void diagonalPrint ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; q . add ( null ) ; while ( q . size ( ) > 0 ) { Node temp = q . peek ( ) ; q . remove ( ) ; if ( temp == null ) { if ( q . size ( ) == 0 ) return ; System . out . println ( ) ; q . add ( null ) ; } else { while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; if ( temp . left != null ) q . add ( temp . left ) ; temp = temp . right ; } } } } public static void main ( String args [ ] ) { Node root = newNode ( 8 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 10 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 6 ) ; root . right . right = newNode ( 14 ) ; root . right . right . left = newNode ( 13 ) ; root . left . right . left = newNode ( 4 ) ; root . left . right . right = newNode ( 7 ) ; diagonalPrint ( root ) ; } }