Simple Java DFS, 10 ms, 88%


  • 0
    V
        List<Integer> toRet;
        public List<Integer> largestValues(TreeNode root) 
        {
            toRet = new ArrayList<Integer>();
            dfs(root, 1);
            return toRet;
        }
        void dfs(TreeNode root, int lvl)
        {
            if(root == null)
                return;
            if(toRet.size() < lvl)
                toRet.add(root.val);
            else
                toRet.set(lvl - 1, Math.max(root.val, toRet.get(lvl - 1)));
            dfs(root.left, lvl + 1);
            dfs(root.right, lvl + 1);
        }

Log in to reply
 

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