题目描述
解法:层遍历(C++)
思路很简单,就是层遍历到该层最右的节点,就将这个节点的值放入结果数组中
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(root==nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int n = q.size();
for(int i=0;i<n;i++)
{
TreeNode* tmp = q.front();
q.pop();
if(tmp->left!=nullptr) q.push(tmp->left);
if(tmp->right!=nullptr) q.push(tmp->right);
if(i==n-1) res.push_back(tmp->val);
}
}
return res;
}
};