Thursday, July 8, 2021

LeetCode 760 · Binary Tree Right Side View.java

// There is a little improvement from regular BFS,
// This question needs to read the last one, and the queue does not support it.
// But ArrayDeque itself does support it, so you only need to use the Deque interface, and you can play as you like.
public class Solution {
/**
* @param root: the root of the given tree
* @return: the values of the nodes you can see ordered from top to bottom
*/
public List<Integer> rightSideView(TreeNode root) {
// write your code here
if (root == null) {
return new LinkedList<>();
}
return bfs(root);
}
private List<Integer> bfs(TreeNode root) {
List<Integer> list = new LinkedList<>();
Deque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
list.add(queue.peekLast().val);
while (size-- > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return list;
}
}

No comments:

Post a Comment