Recursive java solution


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

Log in to reply
 

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