import java.util.*;
public class Main {
/**
//该段代码仅用于调试,提交时请注释该段代码
class TreeNode<T> {
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
}
*/
public int solution(TreeNode<Integer> root) {
if (root == null) {
return 0;
}
List<TreeNode> list1 = new ArrayList<>();
List<TreeNode> list2 = new ArrayList<>();
list1.add(root);
int maxWidth = 0;
while (!list1.isEmpty() || !list2.isEmpty()) {
if (!list1.isEmpty()) {
int size = list1.size();
if (size > maxWidth) {
maxWidth = size;
}
for (int i = 0; i < size; i++) {
TreeNode node = list1.get(i);
if (node.left != null) {
list2.add(node.left);
}
if (node.right != null) {
list2.add(node.right);
}
}
list1.clear();
} else {
int size = list2.size();
if (size > maxWidth) {
maxWidth = size;
}
for (int i = 0; i < size; i++) {
TreeNode node = list2.get(i);
if (node.left != null) {
list1.add(node.left);
}
if (node.right != null) {
list1.add(node.right);
}
}
list2.clear();
}
}
return maxWidth;
}
}