-
Notifications
You must be signed in to change notification settings - Fork 0
/
P120.java
43 lines (41 loc) · 1001 Bytes
/
P120.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.*;
import java.io.*;
/************************************************************
*
* Following is the TreeNode class structure
*
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
*
* TreeNode(int val) {
* this.val = val;
* this.left = null;
* this.right = null;
* }
* }
*
*
************************************************************/
public class P120 {
public static int getMaxWidth(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int ans = 0;
while (!q.isEmpty()) {
int size = q.size();
ans = Math.max(ans, size);
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
if (curr.left != null)
q.add(curr.left);
if (curr.right != null)
q.add(curr.right);
}
}
return ans;
}
}