# LC 199. Binary Tree Right Side View
### [Problem link](https://leetcode.com/problems/binary-tree-right-side-view/)
###### tags: `leedcode` `medium` `python` `c++` `Binary Tree`
Given the <code>root</code> 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:**
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" style="width: 401px; height: 301px;" />
```
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
```
**Example 2:**
```
Input: root = [1,null,3]
Output: [1,3]
```
**Example 3:**
```
Input: root = []
Output: []
```
**Constraints:**
- The number of nodes in the tree is in the range <code>[0, 100]</code>.
- <code>-100 <= Node.val <= 100</code>
## Solution 1
#### Python
```python=
# iteration
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
if not root:
return []
q = deque([root])
while q:
size_q = len(q)
for i in range(size_q):
node = q.popleft()
if i == size_q - 1:
res.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
```
```python=
# recursive
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
def bfs(node, depth):
if not node:
return []
if depth == len(res):
res.append([])
res[depth].append(node.val)
if node.left:
bfs(node.left, depth + 1)
if node.right:
bfs(node.right, depth + 1)
bfs(root, 0)
return [i[-1] for i in res]
```
#### C++
```cpp=
// iteration
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
queue<TreeNode*> q;
if (root != nullptr) {
q.push(root);
}
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode *node = q.front();
q.pop();
if (i == size - 1) {
res.push_back(node->val);
}
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
return res;
}
};
```
```cpp=
// recursive
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> ans;
void dfs(TreeNode *node, int depth) {
if (node == nullptr) {
return;
}
if (depth == ans.size()) {
ans.push_back(node->val);
}
dfs(node->right, depth + 1);
dfs(node->left, depth + 1);
}
vector<int> rightSideView(TreeNode* root) {
dfs(root, 0);
return ans;
}
};
```
>### Complexity
>n = number of tree’s nodes
>l = number of tree's level nodes
>| | Time Complexity | Space Complexity |
>| ---------------------- | --------------- | ---------------- |
>| Solution 1(iteration) | O(n) | O(l) |
>| Solution 1(recursive) | O(n) | O(n) |
## Note
solution1:
iteration: 每次只處理一層, 所以SC: O(l)
recursive: 讀取完全部的node再輸出res, 所以SC: O(l)