# 199. Binary Tree Right Side View -BFS

![](/files/-Mbsp_BWctG4fbucMzq8)

![](/files/-Mbspbt9WwKLUG6scfyY)

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);
    }
}
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/tree/199.-binary-tree-right-side-view.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
