Java using Map


  • 0
    E
    public List<Integer> largestValues(TreeNode root) {
            Map<Integer, Integer> rowLargest = new HashMap<>();
            helper(root, rowLargest, 0);
            return new ArrayList<>(rowLargest.values());
        }
        
        private void helper(TreeNode root, Map<Integer, Integer> rowLargest, int row) {
            if(root == null) return;
            if(rowLargest.keySet().size() == row) {
                rowLargest.put(row, root.val);   
            }else {
                rowLargest.put(row, Math.max(rowLargest.get(row), root.val));    
            }
            helper(root.left, rowLargest, row + 1);
            helper(root.right, rowLargest, row + 1);
        }
    

Log in to reply
 

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