image.png

思路:

  • 还是标准的层次遍历二叉树,如果当前层大小为0,说明已经遍历到最右边那个节点了
  • 队列的大小就是当前层的大小,这是理解的关键所在

代码:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<int> rightSideView(TreeNode* root) {
  15. vector<int> right_view_vals;
  16. if(!root) {
  17. return right_view_vals;
  18. }
  19. queue<TreeNode*> q;
  20. q.push(root);
  21. while (!q.empty()) {
  22. // cur_level_size 就是 q 的大小,这一点很关键
  23. int cur_level_size = q.size();
  24. while (cur_level_size--) {
  25. TreeNode* node = q.front();
  26. if (cur_level_size == 0) {
  27. right_view_vals.push_back(node->val);
  28. }
  29. q.pop();
  30. if (node->left) {
  31. q.push(node->left);
  32. }
  33. if (node->right) {
  34. q.push(node->right);
  35. }
  36. }
  37. }
  38. return right_view_vals;
  39. }
  40. };