Given 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.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
void printRight(vector<int> &res,TreeNode *root,int cur,int &max){
if(!root)
return;
if(cur>max){
res.push_back(root->val);
max=cur;
}
printRight(res,root->right,cur+1,max);
printRight(res,root->left,cur+1,max);
}
vector<int> rightSideView(TreeNode *root) {
vector<int> res;
int max = -1;
printRight(res,root,0,max);
return res;
}