这道题目是二叉树的层序遍历的扩展,对二叉树进行层序遍历,判断节点是否为该层的最后一个节点,如果是,则将其的数值添加到返回数组中。
/*** 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> result;queue<TreeNode*> que;if(root != nullptr){que.push(root);}while(!que.empty()){int size = que.size();for(int i = 0; i < size; i++){TreeNode* cur = que.front();que.pop();if(i == size - 1){result.push_back(cur->val);}if(cur->left != nullptr) {que.push(cur->left);}if(cur->right != nullptr) {que.push(cur->right);}}}return result;}
};