Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Last active September 26, 2019 17:22
Show Gist options
  • Save shixiaoyu/9f0389b2e4ce2a1bad9425b9edc3c90d to your computer and use it in GitHub Desktop.
Save shixiaoyu/9f0389b2e4ce2a1bad9425b9edc3c90d to your computer and use it in GitHub Desktop.
// BFS with a queue
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
// need to put node in the queue, not value
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int s = q.size();
// classic template for bfs, remember the queue size is the current level
for (int i = 0; i < s; i++) {
TreeNode t = q.poll();
// the last element is right side view
if (i == s - 1) {
res.add(t.val);
}
if (t.left != null) q.offer(t.left);
if (t.right != null) q.offer(t.right);
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment