-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeRightSideView.java
36 lines (33 loc) · 1.01 KB
/
BinaryTreeRightSideView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package tree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeRightSideView {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> rv= new ArrayList<>();
Queue<TreeNode> q = new LinkedList();
List<Integer>vals= new ArrayList();
if(root!=null){
q.offer(root) ;
q.offer(null);
while(!q.isEmpty()) {
TreeNode tmp= q.poll();
if(tmp!=null){
vals.add(tmp.val);
if(tmp.left!=null)
q.offer(tmp.left) ;
if(tmp.right!=null)
q.offer(tmp.right);
}else{
//Level is reached
rv.add(vals.get(vals.size()-1));
vals.clear();
if(!q.isEmpty())
q.offer(null);
}
}
}
return rv;
}
}