Q:给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
A:
层次遍历,取每层最后一个。
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
while (!q.isEmpty()) {
while (size != 0) {
if (size == 1) {
res.add(q.peek().val);
}
TreeNode curr = q.poll();
if (curr.left != null) {
q.add(curr.left);
}
if (curr.right != null) {
q.add(curr.right);
}
size--;
}
size = q.size();
}
return res;
}