-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path199_BinaryTreeRightSideView
More file actions
60 lines (53 loc) · 1.61 KB
/
199_BinaryTreeRightSideView
File metadata and controls
60 lines (53 loc) · 1.61 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
199. Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
// use queue();
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
Queue<TreeNode> sameLevel = new LinkedList<>();
TreeNode tmp = null;
while(!q.isEmpty()) {
tmp = q.poll();
if (tmp.left != null) {
sameLevel.offer(tmp.left);
}
if (tmp.right != null) {
sameLevel.offer(tmp.right);
}
}
q = sameLevel;
list.add(tmp.val);
}
return list;
}
}
other's solution:
public List<Integer> rightSideView(TreeNode root) {
if(root==null)
return new ArrayList<Integer>();
List<Integer> left = rightSideView(root.left);
List<Integer> right = rightSideView(root.right);
List<Integer> re = new ArrayList<Integer>();
re.add(root.val);
for(int i=0;i<Math.max(left.size(), right.size());i++){
if(i>=right.size())
re.add(left.get(i));
else
re.add(right.get(i));
}
return re;
}