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.
Example 1:
Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
Example 2:
Input: root = [1,null,3] Output: [1,3]
Example 3:
Input: root = [] Output: []
Constraints:
[0, 100]
.-100 <= Node.val <= 100
class Solution {
public:
vector rightSideView(TreeNode* root) {
if(root==NULL)return {};
map mpp;
queue> q;
q.push({0,root});
while(!q.empty())
{
auto it=q.front();
q.pop();
TreeNode* node=it.second;
int level= it.first;
if(mpp.find(level)==mpp.end()) mpp[level]=node->val;
if(node->right) q.push({level+1, node->right});
if(node->left) q.push({level+1, node->left});
}
vector ans;
for(auto i: mpp)
{
ans.push_back(i.second);
}
return ans;
}
};
class Solution {
public List rightSideView(TreeNode root) {
List ans = new ArrayList<>();
helper(root,ans , 0);
return ans ;
}
// modified Preorder Traversal --> Node --> Right --> left
public void helper (TreeNode root , List ans , int level ){
if(root == null){
return ;
}
if(ans.size()==level){
ans.add(root.val);
}
helper(root.right , ans , level+1 );
helper(root.left,ans , level+1);
}
}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India