1 /* 2 * @lc app=leetcode.cn id=199 lang=cpp 3 * 4 * [199] 二叉树的右视图 5 */ 6 7 // @lc code=start 8 /** 9 * Definition for a binary tree node. 10 * struct TreeNode { 11 * int val; 12 * TreeNode *left; 13 * TreeNode *right; 14 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 * }; 16 */ 17 class Solution { 18 public: 19 //使用层序遍历,并只保留每层最后一个节点的值 20 //while(size--)在层序遍历中的应用 21 vector<int> rightSideView(TreeNode* root) { 22 vector<int> res; 23 if(root==nullptr) return res; 24 queue<TreeNode*> q; 25 q.push(root); 26 while (!q.empty()) 27 { 28 int size=q.size(); 29 res.push_back(q.back()->val); 30 while(size--){ 31 TreeNode *tmp=q.front(); 32 q.pop(); 33 if(tmp->left) q.push(tmp->left); 34 if(tmp->right) q.push(tmp->right); 35 } 36 } 37 return res; 38 } 39 }; 40 // @lc code=end