Java DFS with Depth, Recursive solution.


  • 0
    M
    public List<Integer> largestValues(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if(root==null)
                return result;
            largestValues(root,0,result);
            return result;
        }
        
        public void largestValues(TreeNode root, int depth, List<Integer> result){
            if(root==null)
                return;
            if(result.size()==depth){
                result.add(root.val);
            }else{
                if(root.val > result.get(depth)){
                    result.set(depth, root.val);
                }
            }
            largestValues(root.left,depth+1,result);
            largestValues(root.right,depth+1,result);
        }
    

Log in to reply
 

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