Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
/**
* 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> rightSideView(TreeNode* root) {
vector<int> values;
if (root == nullptr) return values;
vector<TreeNode*> current{root};
vector<TreeNode*> next;
while (!current.empty()){
values.emplace_back(current.front()->val);
for (const auto &node: current) {
if (node->right != nullptr) next.emplace_back(node->right);
if (node->left != nullptr) next.emplace_back(node->left);
}
current.swap(next);
next.clear();
}
return values;
}
};