class RecentCounter {
public RecentCounter();
public int ping(int t);
}
class RecentCounter {
private Queue<Integer> times;
private int windowSize;
public RecentCounter() {
times = new LinkedList<>();
windowSize = 3000;
}
public int ping(int t) {
times.offer(t);
while (times.peek() + windowSize < t) {
times.poll();
}
return times.size();
}
}
class CBTInserter {
private Queue<TreeNode> queue;
private TreeNode root;
public CBTInserter(TreeNode root) {
this.root = root;
queue = new LinkedList<>();
queue.offer(root);
while (queue.peek().left != null && queue.peek().right != null) {
TreeNode node = queue.poll();
queue.offer(node.left);
queue.offer(node.right);
}
}
public int insert(int v) {
TreeNode parent = queue.peek();
TreeNode node = new TreeNode(v);
if (parent.left == null) {
parent.left = node;
} else {
parent.right = node;
queue.poll();
queue.offer(parent.left);
queue.offer(parent.right);
}
return parent.val;
}
public TreeNode get_root() {
return root;
}
}
public List<Integer> largestValues(TreeNode root) {
int current = 0;
int next = 0;
Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.offer(root);
current = 1;
}
List<Integer> result = new LinkedList<>();
int max = Integer.MIN_VALUE;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
current--;
max = Math.max(max, node.val);
if (node.left != null) {
queue.offer(node.left);
next++;
}
if (node.right != null) {
queue.offer(node.right);
next++;
}
if (current == 0) {
result.add(max);
max = Integer.MIN_VALUE;
current = next;
next = 0;
}
}
return result;
}
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue1 = new LinkedList<>();
Queue<TreeNode> queue2 = new LinkedList<>();
queue1.offer(root);
int bottomLeft = root.val;
while(!queue1.isEmpty()) {
TreeNode node = queue1.poll();
if (node.left != null) {
queue2.offer(node.left);
}
if (node.right != null) {
queue2.offer(node.right);
}
if (queue1.isEmpty()) {
queue1 = queue2;
queue2 = new LinkedList<>();
if (!queue1.isEmpty()) {
bottomLeft = queue1.peek().val;
}
}
}
return bottomLeft;
}
public List<Integer> rightSideView(TreeNode root) {
List<Integer> view = new LinkedList<Integer>();
if (root == null) {
return view;
}
Queue<TreeNode> queue1 = new LinkedList<>();
Queue<TreeNode> queue2 = new LinkedList<>();
queue1.offer(root);
while (!queue1.isEmpty()) {
TreeNode node = queue1.poll();
if (node.left != null) {
queue2.offer(node.left);
}
if (node.right != null) {
queue2.offer(node.right);
}
if (queue1.isEmpty()) {
view.add(node.val);
queue1 = queue2;
queue2 = new LinkedList<>();
}
}
return view;
}