2ms dfs Java solution with notes


  • 1
    L
    public class Solution {
    private int maxHeight;
    private int curHeight;
    private final List<Integer> path = new ArrayList<Integer>();
    
    public List<Integer> rightSideView(TreeNode root) {
        if(root == null) return path;
        path.add(root.val);
        if(root.left == null && root.right == null){
            return path;
        }
        if(root.right != null){
            dfs(root.right);
        }
        if(root.left != null){
            dfs(root.left);
        }
        return path;
    }
    /**
     * use depth-first-search to keep track of the path, right nodes get higher priority than left
     * current height increments whenever program enters dfs; it decrements right before dfs returns
     * max height increments if current height is larger than max height, node added to path at the same time
     * 
     * @param current
     * current node doing dfs
     */
    private void dfs(TreeNode current){
        curHeight++;
        if(curHeight>maxHeight){
            path.add(current.val);
            maxHeight++;
        }
        if(current.right!=null){
            dfs(current.right);
        }
        if(current.left!=null){
            dfs(current.left);
        }
        curHeight--;
    }
    

    }


Log in to reply
 

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