efficient method soo follow this for better result
class Solution {
public:
vector<int> res;
void rightfunc(TreeNode * root ,int level){
if(root == NULL) return;
if(level == res.size()){
res.push_back(root->val);
}
rightfunc(root->right , level+1);
rightfunc(root->left, level+1);
}
vector<int> rightSideView(TreeNode* root) {
rightfunc(root ,0);
return res;
}
};
its too big and interviewer will not be happy
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int > res;
vector<vector<int >> levelOrder;
levelOrder = levelorder(root);
for(auto it : levelOrder){
res.push_back(it.back());
}
return res;
}
private:
vector<vector<int>> levelorder(TreeNode* root){
vector<vector<int>> res;
if(!root){
return res;
}
queue <TreeNode* > q;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int> level;
for(int i =0 ; i< size; i++){
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if(node->left !=NULL){
q.push(node->left);
}
if(node->right !=NULL){
q.push(node->right);
}
}
res.push_back(level);
}
return res;
}
};