层序遍历【从右往左】
/**
* 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> ans;
queue<TreeNode*> q[2];
int f=0;
if(root) q[f].push(root);
while(!q[f].empty()){
ans.push_back(q[f].front()->val);
while(!q[f].empty()){
auto x=q[f].front();q[f].pop();
if(x->right) q[1-f].push(x->right);
if(x->left) q[1-f].push(x->left);
}
f^=1;
}
return ans;
}
};