Java DFS 8 lines beat 88%


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     
     /*
        bfs: for each iteration find max value of each level
        dfs: list of max using level as index:
            
     */
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> values = new ArrayList<>();
            dfs(root, 0, values);
            return values;
        }
        
        public void dfs(TreeNode node, int level, List<Integer> values) {
            if (node == null) return;
            if (values.size() <= level) values.add(node.val);
            else values.set(level, Math.max(node.val, values.get(level)));
            dfs(node.left, level + 1, values);
            dfs(node.right, level + 1, values);
        }
    }
    
    

Log in to reply
 

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