JAVA solution using recursion


  • 10
    J
    public class Solution {
    
    
     public List<Integer> rightSideView(TreeNode root) {
    		ArrayList<Integer> result = new ArrayList<Integer>();
    		if (root == null) return result;
    		return helper(root, result, 0);
    	}
    
    public List<Integer> helper(TreeNode root, ArrayList<Integer> result,
    		int height) {
    	if (height == result.size()) {
    		result.add(root.val);
    	}
    
    	if (root.right != null) {
    		helper(root.right, result, height + 1);
    
    	}
    	if (root.left != null) {
    		helper(root.left, result, height + 1);
    	}
    	return result;
    }
    

    }

    Comments: height == result.size() is the core part in this recursion, it limits the amount of Node add to the result in each level(height) of the Tree.

    Some thoughts: If the questions is asking for a left view of the binary tree, just swap the order of

    if (root.right != null) {
    		helper(root.right, result, height + 1);
    
    	}
    

    and

    if (root.left != null) {
        helper(root.left, result, height + 1);
    }
    

    Moreover, if it's asking of the "x-ray view" of the binary tree, for example, display the second element from the right view(given a valid tree). The solution could be adding a counter inside

    if (height == result.size()) {
    	result.add(root.val);
    }
    

    and keep track of the counter.


Log in to reply
 

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