解題思路
利用雙端隊(duì)列進(jìn)行廣度優(yōu)先遍歷稀拐,將每一層的最后的節(jié)點(diǎn)加入結(jié)果集
代碼
class Solution {
public List<Integer> rightSideView(TreeNode root) {
LinkedList<Integer> result = new LinkedList<>();
if (root == null) {
return result;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.addLast(root);
while (!deque.isEmpty()) {
int size = deque.size();
result.add(deque.getLast().val);
for (int i = 0; i < size; i++) {
TreeNode head = deque.removeFirst();
if (head.left != null) {
deque.addLast(head.left);
}
if (head.right != null) {
deque.addLast(head.right);
}
}
}
return result;
}
}