Vertical width of Binary tree | Set 2 | CPP code to find vertical width of a binary tree ; Tree class ; Function to fill hd in set . ; Third parameter is horizontal distance ; Driver Code ; Creating the above tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data_new ) { data = data_new ; left = right = NULL ; } } ; void fillSet ( Node * root , unordered_set < int > & s , int hd ) { if ( ! root ) return ; fillSet ( root -> left , s , hd - 1 ) ; s . insert ( hd ) ; fillSet ( root -> right , s , hd + 1 ) ; } int verticalWidth ( Node * root ) { unordered_set < int > s ; fillSet ( root , s , 0 ) ; return s . size ( ) ; } int main ( ) { Node * root = NULL ; root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; 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 -> right -> left -> right = new Node ( 8 ) ; root -> right -> right -> right = new Node ( 9 ) ; cout << verticalWidth ( root ) << " STRNEWLINE " ; return 0 ; }