Vertical width of Binary tree | Set 1 | CPP program to print vertical width of a tree ; A Binary Tree Node ; get vertical width ; traverse left ; if curr is decrease then get value in minimum ; if curr is increase then get value in maximum ; traverse right ; 1 is added to include root in the width ; Utility function to create a new tree node ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void lengthUtil ( Node * root , int & maximum , int & minimum , int curr = 0 ) { if ( root == NULL ) return ; lengthUtil ( root -> left , maximum , minimum , curr - 1 ) ; if ( minimum > curr ) minimum = curr ; if ( maximum < curr ) maximum = curr ; lengthUtil ( root -> right , maximum , minimum , curr + 1 ) ; } int getLength ( Node * root ) { int maximum = 0 , minimum = 0 ; lengthUtil ( root , maximum , minimum , 0 ) ; return ( abs ( minimum ) + maximum ) + 1 ; } Node * newNode ( int data ) { Node * curr = new Node ; curr -> data = data ; curr -> left = curr -> right = NULL ; return curr ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; cout << getLength ( root ) << " STRNEWLINE " ; return 0 ; }