Question 39 of 75 - LeetCode Weekly Challenge
Day 87 of 100 Days LeetCode Challenge

LeetCode Challenge #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.

 

Example 1:

tree

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:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
C++ Video Solution
Java Video Solution
C++ Solution
				
					class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {

         if(root==NULL)return {};
        map<int,int> mpp;
        queue<pair<int, TreeNode*>> 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<int> ans;
        for(auto i: mpp)
        {
            ans.push_back(i.second);
        }

        return ans;
    }
};
				
			
Java Solution
				
					class Solution {
    public List<Integer> rightSideView(TreeNode root) {
     List<Integer> ans = new ArrayList<>();
     helper(root,ans , 0);
     return ans ;
    }
// modified Preorder Traversal --> Node --> Right --> left 
    public void helper (TreeNode root , List<Integer> 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);
    }
}
				
			

Happy Coding with edSlash