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 List<Integer> rightSideView(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
if(root==null)
return result;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode node=queue.poll();
if(i==0)
result.add(node.val);
if(node.right!=null)
queue.add(node.right);
if(node.left!=null)
queue.add(node.left);
}
}
return result;
}