思路:
- 还是标准的层次遍历二叉树,如果当前层大小为0,说明已经遍历到最右边那个节点了
- 队列的大小就是当前层的大小,这是理解的关键所在
代码:
/**
* 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> right_view_vals;
if(!root) {
return right_view_vals;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
// cur_level_size 就是 q 的大小,这一点很关键
int cur_level_size = q.size();
while (cur_level_size--) {
TreeNode* node = q.front();
if (cur_level_size == 0) {
right_view_vals.push_back(node->val);
}
q.pop();
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
return right_view_vals;
}
};