-
-
Save shixiaoyu/9f0389b2e4ce2a1bad9425b9edc3c90d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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