【leetcode 199】binary tree right side view 二叉树的右视图

“The Linux philosophy is “Laugh in the face of danger”.Oops.Wrong One. “Do it yourself”. Yes, that”s it.”
Linux的哲学就是“在危险面前放声大笑”,呵呵,不是这句,应该是“一切靠自己,自力更生”才对。

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

* 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
*
* 层次遍历,输出每一行末尾节点
*/
public class {


* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public static List<Integer> rightSideView (TreeNode root) {
List<Integer> res = new LinkedList<>();
if (root == null)
return res;
Queue<TreeNode> queue = new LinkedList<>();
int size = 1;
queue.offer(root);
while (!queue.isEmpty()) {
res.add((((LinkedList<TreeNode>) queue).peekLast().val));
for (int i = 0; i < size; i++) {
TreeNode r = queue.poll();
if (r.left != null)
queue.offer(r.left);
if (r.right != null)
queue.offer(r.right);
}
size = queue.size();
}
return res;
}
}