Diagonal Traversal of Binary Tree | C ++ program for diagnoal traversal of Binary Tree ; Tree node ; root - root of the binary tree d - distance of current line from rightmost - topmost slope . diagonalPrint - multimap to store Diagonal elements ( Passed by Reference ) ; Base case ; Store all nodes of same line together as a vector ; Increase the vertical distance if left child ; Vertical distance remains same for right child ; Print diagonal traversal of given binary tree ; create a map of vectors to store Diagonal elements ; Utility method to create a new node ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void diagonalPrintUtil ( Node * root , int d , map < int , vector < int > > & diagonalPrint ) { if ( ! root ) return ; diagonalPrint [ d ] . push_back ( root -> data ) ; diagonalPrintUtil ( root -> left , d + 1 , diagonalPrint ) ; diagonalPrintUtil ( root -> right , d , diagonalPrint ) ; } void diagonalPrint ( Node * root ) { map < int , vector < int > > diagonalPrint ; diagonalPrintUtil ( root , 0 , diagonalPrint ) ; cout << " Diagonal ▁ Traversal ▁ of ▁ binary ▁ tree ▁ : ▁ STRNEWLINE " ; for ( auto it : diagonalPrint ) { vector < int > v = it . second ; for ( auto it : v ) cout << it << " ▁ " ; cout << endl ; } } Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int main ( ) { 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 ) ; return 0 ; }