Iterative diagonal traversal of binary tree | C # 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 ; Enqueue root ; Enqueue delimiter ; if current is delimiter then insert another for next diagonal and cout nextline ; if queue is empty return ; output nextline ; Enqueue delimiter again ; if left child is present Enqueue into queue ; current equals to right child ; Driver Code
using System ; using System . Collections ; class GFG { public class Node { public int data ; public 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 q = new Queue ( ) ; q . Enqueue ( root ) ; q . Enqueue ( null ) ; while ( q . Count > 0 ) { Node temp = ( Node ) q . Peek ( ) ; q . Dequeue ( ) ; if ( temp == null ) { if ( q . Count == 0 ) return ; Console . WriteLine ( ) ; q . Enqueue ( null ) ; } else { while ( temp != null ) { Console . Write ( temp . data + " ▁ " ) ; if ( temp . left != null ) q . Enqueue ( 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 ) ; } }