# 199. Binary Tree Right Side View
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 <---
# Solution
Either bfs or dfs, while making sure we keep the rightmost node -- need to visit all nodes to make sure we don't miss any children.
Approach 1: DFS.
Approach 2: BFS.
# Code (Python)
Approach 1:
from collections import deque
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
result = []
queue = deque([(root, 0)])
while queue:
node, level = queue.popleft()
if len(result) == level:
result.append(node.val)
else:
result[-1] = node.val
if node.left:
queue.append((node.left, level + 1))
if node.right:
queue.append((node.right, level + 1))
return result
# Code (C++)
Approach 1:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// DFS.
class Solution {
private:
vector<int> view;
void doRightSideView(TreeNode* root, int level) {
if (root == NULL)
return;
if (level == view.size())
view.push_back(root->val);
else
view[level] = root->val;
doRightSideView(root->left, level + 1);
doRightSideView(root->right, level + 1);
}
public:
vector<int> rightSideView(TreeNode* root) {
doRightSideView(root, 0);
return view;
}
};
Approach 2:
// BFS
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> view;
queue<TreeNode*> q;
if (root)
q.push(root);
while (!q.empty())
{
int qSize = q.size();
TreeNode *node = NULL;
for (int i = 0; i < qSize; ++i)
{
node = q.front();
q.pop();
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
}
view.push_back(node->val);
}
return view;
}
};