# 199. Binary Tree Right Side View

Given the `root` of 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 1:**

![](https://assets.leetcode.com/uploads/2021/02/14/tree.jpg)

<pre><code><strong>Input: root = [1,2,3,null,5,null,4]
</strong><strong>Output: [1,3,4]
</strong></code></pre>

***My Solution:***

DFS:

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res, 0);
        return res;
    }

    private void helper(TreeNode root, List<Integer> res, int level) {
        if (root == null) return;
        if (level == res.size()) res.add(root.val); // this line will add one element to result for one level only
        helper(root.right, res, level + 1); // go to right side first
        helper(root.left, res, level + 1);
    }
}
```

BFS：

按照level order traversal的理念，先加入node的左节点，再加入右节点。每一次只把每个level最后一个node放进result，因为这个是最右节点

```java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        
        if (root == null) return result;
        
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
                if (i == size - 1) {
                    result.add(node.val);
                }
            }
        }
       return result;
    }
}
```
