Iterative diagonal traversal of binary tree | A binary tree node has data , pointer to left child and a pointer to right child ; Function to print diagonal view ; base case ; queue of treenode ; Append root ; Append delimiter ; If current is delimiter then insert another for next diagonal and cout nextline ; If queue is empty then return ; Print output on nextline ; append delimiter again ; If left child is present append into queue ; current equals to right child ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . val = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def diagonalprint ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT temp = q . pop ( 0 ) NEW_LINE if not temp : NEW_LINE INDENT if len ( q ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT print ( ' ▁ ' ) NEW_LINE q . append ( None ) NEW_LINE DEDENT else : NEW_LINE INDENT while temp : NEW_LINE INDENT print ( temp . val , end = ' ▁ ' ) NEW_LINE if temp . left : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT temp = temp . right NEW_LINE DEDENT DEDENT DEDENT DEDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 10 ) NEW_LINE root . left . left = Node ( 1 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE root . right . right . left = Node ( 13 ) NEW_LINE root . left . right . left = Node ( 4 ) NEW_LINE root . left . right . right = Node ( 7 ) NEW_LINE diagonalprint ( root ) NEW_LINE