-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeRightSideView.java
More file actions
34 lines (32 loc) · 923 Bytes
/
Copy pathBinaryTreeRightSideView.java
File metadata and controls
34 lines (32 loc) · 923 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
if(root == null) return Collections.emptyList();
TreeNode dummy = new TreeNode(0);
Queue<TreeNode> p = new ArrayDeque<>();
p.offer(root);
p.offer(dummy);
List<Integer> result = new ArrayList<>();
int right = 0;
while(!p.isEmpty()) {
TreeNode t = p.poll();
if(t != dummy) {
right = t.val;
if(t.left != null) p.offer(t.left);
if(t.right != null) p.offer(t.right);
}else {
if(!p.isEmpty()) p.offer(dummy);
result.add(right);
}
}
return result;
}
}