# 199. Binary Tree Right Side View -BFS

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MbpwZObtwifmBjmSGZB%2F-Mbsp_BWctG4fbucMzq8%2Fimage.png?alt=media\&token=f0412789-b3a0-4b61-9184-f31cd47f93e0)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MbpwZObtwifmBjmSGZB%2F-Mbspbt9WwKLUG6scfyY%2Fimage.png?alt=media\&token=7a07f27e-dcec-4d2e-82c6-24375c14a6fe)



this part  is the key point

```java
if (i == 0) {
    res.add(cur.val);
}
// right first, so i == 0 is the right side's first node
if (cur.right != null) queue.offer(cur.right); 
if (cur.left != null) queue.offer(cur.left);
```

or

```java
if (i == size - 1) {
    res.add(cur.val);
}
// or left, right, so size - 1 is the right side's first node
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);

```



time: O(n)

space: O(D) to keep the queues, where D is a tree diameter. Let's use the last level to estimate the queue size. This level could contain up to N/2N/2 tree nodes in the case of [complete binary tree](https://leetcode.com/problems/count-complete-tree-nodes/).

```java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        
        Queue<TreeNode> queue = new LinkedList<>();
        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;
    }
}
```



## DFS

use preorder (because not related to subtree)

how to know current depth? use a varible

````java
```java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, result, 1);
        return result;
    }
    private void dfs(TreeNode node, List<Integer> result, int depth) {
        if (node == null) {
            return;
        }

        if (depth > result.size()) {
            result.add(node.val);
        }
        dfs(node.right, result, depth + 1);
        dfs(node.left, result, depth + 1);
    }
}
```
````
