二叉树的右视图
/**
* 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) {
//宽度遍历二叉树的题型
//返回的是每一层的最后一个元素的数值
//使用一个flag进行计算
int thislevel=1;
int nextlevel=0;
queue<TreeNode*> q;
vector<int> result;
if(root==NULL)
return result;
//不用使用vector保存数据,等到遇到再说
q.push(root);
while(!q.empty())
{
TreeNode* temp=q.front();
q.pop();
--thislevel;
if(temp->left)
{
q.push(temp->left);
++nextlevel;
}
if(temp->right)
{
q.push(temp->right);
++nextlevel;
}
//如果满足是这行最后一个数字条件输出这个数字
if(thislevel==0)
{
result.push_back(temp->val);
thislevel=nextlevel;
nextlevel=0;
}
}
return result;
}
};