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]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
return bfs(root);
}
private List<Integer> bfs(TreeNode root){
if(root==null) return new ArrayList<Integer>();
Queue<TreeNode> cur = new LinkedList<>();
Queue<TreeNode> next = new LinkedList<>();
cur.offer(root);
List<Integer> res = new ArrayList<>();
while(!cur.isEmpty()){
res.add(cur.peek().val);
while(!cur.isEmpty()){
TreeNode t = cur.poll();
if(t.right!=null) next.offer(t.right);
if(t.left!=null) next.offer(t.left);
}
Queue<TreeNode> tmp = cur;
cur = next;
next = tmp;
}
return res;
}
}