File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ package Trees ;
2+
3+ import java .util .LinkedList ;
4+ import java .util .Queue ;
5+
6+ public class MaximumWidthOfBinaryTree {
7+ static class TreeNode {
8+ TreeNode root ;
9+ TreeNode left ;
10+ TreeNode right ;
11+
12+ TreeNode () {}
13+ }
14+ public int widthOfBinaryTree (TreeNode root ) {
15+ if (root == null ) return 0 ;
16+ // queue to hold nodes
17+ Queue <TreeNode > q = new LinkedList <>();
18+ // queue to hold index of corresponding node in BFS order
19+ Queue <Integer > qIndex = new LinkedList <>();
20+ // adding first node
21+ q .add (root );
22+ // add first node's index (say 1)
23+ qIndex .add (1 );
24+
25+ int maxWidth = 0 ;
26+ // level order traversal
27+ while (!q .isEmpty ()) {
28+ int size = q .size ();
29+ // store the index of first node in a level
30+ int start = 0 ;
31+ // store the index of last node in a level
32+ int end = 0 ;
33+
34+ for (int i = 0 ; i < size ; i ++) {
35+ // remove from both queues
36+ TreeNode node = q .poll ();
37+ int index = qIndex .poll ();
38+ // if first node
39+ if (i == 0 ) {
40+ // update start index
41+ start = index ;
42+ }
43+ // if last node
44+ if (i == size -1 ) {
45+ // update end index
46+ end = index ;
47+ }
48+ // BFS logic to add left & right node to queue if present.
49+ if (node .left != null ) {
50+ q .add (node .left );
51+ qIndex .add (index *2 );
52+ }
53+
54+ if (node .right != null ) {
55+ q .add (node .right );
56+ qIndex .add (index *2 + 1 );
57+ }
58+ }
59+ // update max width
60+ maxWidth = Math .max (maxWidth , end - start + 1 );
61+ }
62+
63+ return maxWidth ;
64+ }
65+ }
You can’t perform that action at this time.
0 commit comments