forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-right-side-view.java
More file actions
31 lines (29 loc) · 1014 Bytes
/
Copy pathbinary-tree-right-side-view.java
File metadata and controls
31 lines (29 loc) · 1014 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
// Binary Tree Right Side View
// 时间复杂度O(n),空间复杂度O(n)
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
Queue<TreeNode> current = new LinkedList<>();
Queue<TreeNode> next = new LinkedList<>();
if(root == null) {
return result;
} else {
current.offer(root);
}
while (!current.isEmpty()) {
ArrayList<Integer> level = new ArrayList<>(); // elments in one level
while (!current.isEmpty()) {
TreeNode node = current.poll();
level.add(node.val);
if (node.left != null) next.add(node.left);
if (node.right != null) next.add(node.right);
}
result.add(level.get(level.size()-1));
// swap
Queue<TreeNode> tmp = current;
current = next;
next = tmp;
}
return result;
}
}