File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ //This solution helped https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/106645/C%2B%2BJava-*-BFSDFS3liner-Clean-Code-With-Explanation
2
+ //This video helped https://www.youtube.com/watch?v=ZbybYvcVLks&ab_channel=takeUforward
3
+
4
+ class Solution {
5
+ public int widthOfBinaryTree (TreeNode root ) {
6
+ Queue <Pair <TreeNode , Integer >> q = new LinkedList <>();
7
+ int maxWidth = 0 ;
8
+ q .offer (new Pair (root , 1 ));
9
+ while (!q .isEmpty ()) {
10
+ int l = q .peek ().getValue ();
11
+ int r = l ;
12
+ int size = q .size ();
13
+ for (int i = 0 ; i <size ; i ++) {
14
+ TreeNode cur = q .peek ().getKey ();
15
+ r = q .poll ().getValue ();
16
+ if (cur .left !=null )
17
+ q .offer (new Pair (cur .left , 2 *r ));
18
+ if (cur .right !=null )
19
+ q .offer (new Pair (cur .right , 2 *r +1 ));
20
+ }
21
+ maxWidth = Math .max (maxWidth , r -l +1 );
22
+ }
23
+ return maxWidth ;
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments