Java DFS solution


  • 0
    M
        public List<Integer> largestValues(TreeNode root) {
            
            List<Integer> maxValues = new ArrayList<Integer>();
            largestValuesUtil(root, 0, maxValues);
            
            return maxValues;        
        }
        
        private void largestValuesUtil(TreeNode root, int level, List<Integer> maxValues) {
            
            if (root == null) {
                return;
            }
            
            // System.out.println("Currently processing :: Element = " + root.val + " :: level = " + level);
            if (level >= maxValues.size()) {
                // System.out.println("\tNew element added : " + root.val);
                maxValues.add(root.val);
            } else if (maxValues.get(level) < root.val) {
                // System.out.println("\tElement " + maxValues.get(level) + " at level " + level + " is replaced by " + root.val);
                maxValues.set(level, root.val);
            }
            
            largestValuesUtil(root.left, level + 1, maxValues);
            largestValuesUtil(root.right, level + 1, maxValues);
            
        }
    

Log in to reply
 

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