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 <---

题解:

bfs遍历,每次找出每层最右边的数放进去。

class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (root == NULL) {
return ans;
}
queue<TreeNode*> q;
q.push(root);
int size = 1;
while (q.empty() == false) {
TreeNode *p = q.front();
q.pop();
if (p->left != NULL) {
q.push(p->left);
}
if (p->right != NULL) {
q.push(p->right);
}
size--;
if (size == 0) {
ans.push_back(p->val);
size = q.size();
}
}
return ans;
}
};