Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created September 26, 2021 04:03
Show Gist options
  • Save Allan-Gong/76c8cd9bc7fd6b1498387c488fb5d763 to your computer and use it in GitHub Desktop.
Save Allan-Gong/76c8cd9bc7fd6b1498387c488fb5d763 to your computer and use it in GitHub Desktop.
BFS template - 199
class Solution {
// Tree level-traversal
// Graph - BFS
public List<Integer> rightSideView(TreeNode root) {
if (root == null) return Collections.emptyList();
List<Integer> results = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
// System.out.println(queue);
// start looping elements of the current level
// this means the queue has all elements for the current level
results.add(queue.getLast().val);
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment