Vertical width of Binary tree | Set 2 | Java code to find the vertical width of a binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to fill hd in set . ; Third parameter is horizontal distance ; Driver program to test above functions ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
import java . io . * ; import java . util . * ; class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void fillSet ( Node root , Set < Integer > set , int hd ) { if ( root == null ) return ; fillSet ( root . left , set , hd - 1 ) ; set . add ( hd ) ; fillSet ( root . right , set , hd + 1 ) ; } int verticalWidth ( Node root ) { Set < Integer > set = new HashSet < Integer > ( ) ; fillSet ( root , set , 0 ) ; return set . size ( ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . right = new Node ( 8 ) ; tree . root . right . right . left = new Node ( 6 ) ; tree . root . right . right . right = new Node ( 7 ) ; System . out . println ( tree . verticalWidth ( tree . root ) ) ; } }