Java 1 ms beats 80% Depth First Search (DFS)


  • 0
    P
        public List<Integer> rightSideView(TreeNode root) 
        {
            ArrayList<Integer> res = new ArrayList<Integer>();
            
            rightSideViewRec(root, 0, res);
            
            return res;
        }
        
        public void rightSideViewRec(TreeNode node, int layer, ArrayList<Integer> res) 
        {
            if(node == null)
                return;
                
            if(res.size() > layer)
                res.set(layer, node.val);
            else
                res.add(node.val);
                
            if(node.left != null)
                rightSideViewRec(node.left, layer + 1, res);
            if(node.right != null)
                rightSideViewRec(node.right, layer + 1, res); 
        }
    
    

Log in to reply
 

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