[Oracle] LeetCode 199 Binary Tree Right Side View
Given the root
of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Solution
点击查看代码
/**
* 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 {
private:
vector<int> ans;
queue<TreeNode*> q;
public:
vector<int> rightSideView(TreeNode* root) {
if(!root)return ans;
q.push(root);ans.push_back(root->val);
while(!q.empty()){
int sz = q.size();
int fg=0;
for(int i=0;i<sz;i++){
auto f=q.front();q.pop();
if(f->right){
if(!fg)ans.push_back(f->right->val),fg=1;
q.push(f->right);
}
if(f->left){
if(!fg)ans.push_back(f->left->val),fg=1;
q.push(f->left);
}
}
}
return ans;
}
};