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]
.
BFS层次遍历,每层的最后一个节点就是所求。
public List<Integer> rightSideView(TreeNode root)
{
if(root==null)
return new ArrayList<>();
ArrayDeque<TreeNode> deque=new ArrayDeque<>();
ArrayList<Integer> arraylist=new ArrayList<>();
deque.add(root);
int level=0;
int num=1;
while(!deque.isEmpty())
{
TreeNode t=deque.poll();
if(t.left!=null)
deque.add(t.left);
if(t.right!=null)
deque.add(t.right);
num--;
if(num==0)
{
level++;
num=deque.size();
arraylist.add(t.val);
}
}
return arraylist;
}