Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1bba8c6

Browse files
edit 199
1 parent 2bb2280 commit 1bba8c6

File tree

1 file changed

+18
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-14
lines changed

src/main/java/com/fishercoder/solutions/_199.java

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,28 @@
2323
You should return [1, 3, 4]. */
2424

2525
public class _199 {
26-
//Using BFS is pretty straightforward. But there might be a smarter way.
26+
2727
public List<Integer> rightSideView(TreeNode root) {
28-
List<Integer> res = new ArrayList<Integer>();
29-
if(root == null) return res;
30-
Queue<TreeNode> q = new LinkedList<TreeNode>();
28+
List<Integer> result = new ArrayList<>();
29+
if (root == null) return result;
30+
Queue<TreeNode> q = new LinkedList<>();
3131
q.offer(root);
32-
while(!q.isEmpty()){
33-
int currentSize = q.size();
34-
int i = 0;
35-
TreeNode currentNode = null;
36-
for(; i < currentSize; i++){
37-
currentNode = q.poll();
38-
if(currentNode.left != null) q.offer(currentNode.left);
39-
if(currentNode.right != null) q.offer(currentNode.right);
32+
while (!q.isEmpty()) {
33+
int size = q.size();
34+
for (int i = 0; i < size; i++) {
35+
TreeNode curr = q.poll();
36+
if (i == size-1) {
37+
result.add(curr.val);
38+
}
39+
if (curr.left != null) {
40+
q.offer(curr.left);
41+
}
42+
if (curr.right != null) {
43+
q.offer(curr.right);
44+
}
4045
}
41-
res.add(currentNode.val);
4246
}
43-
return res;
47+
return result;
4448
}
4549

4650
public static void main(String...strings){

0 commit comments

Comments
 (0)