( bfs is easy, instead use preorder dfs right first and then left)
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.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
// dfs, preorder, right first and then left
// use a var level to know which level we are on, since
// we only add one element on each level , and
// the res size is related to the first node on the new level
// for instsance, level 0, list size is 0, and we add cur node at
// level 0. when we are level one, the list size is 1,
// we add the cur node to the res,
// when we meet another new node at level 1, the current list size is
// 2 , then we know the current node is not the right most node on level 1
//
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
dfs(root, res, 0);
return res;
}
private void dfs(TreeNode root, List<Integer> res, int level){
// base case
if(root == null) return;
if(level == res.size()){
res.add(root.val);
}
dfs(root.right, res, level + 1);
dfs(root.left, res, level + 1);
}
}
// bfs iterative queue , time o(n),
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if(root == null) return res;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.poll();
if(i == 0){
res.add(cur.val);
}
if(cur.right != null) queue.offer(cur.right);
if(cur.left != null) queue.offer(cur.left);
}
}
return res;
}
}