Simple Java solution with in depth comments. 0 ms solution.


  • 1
    P
    public class BinaryTreeRightSideView {
    	int depth = 0; // No depth has been gone through initially.
    
    	public List<Integer> rightSideView(TreeNode root) {
        	List<Integer> res = new ArrayList<>();
    		dfs(root, 1, res); // Initial level should be more than initial depth.
    		return res;
    	}
    
    	private void dfs(TreeNode root, int level, List<Integer> res) {
    		if (root == null)
    			return;
    		if (level > depth) { // Check if the current level is greater than the already seen depth.
    			res.add(root.val);
    			depth++; // Increase depth to check in future.
    		}
    			dfs(root.right, level + 1, res); //Go right first because you're on the right side.
    			dfs(root.left, level + 1, res); // Go left to check whether it has got more depth than the current seen depth.
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.