Solution using DFS


  • 0
    M

    Do DFS and pass level as parameter to function, check on every function call if current node value is largest for the level, if yes, update the level maximum value, here is the implementation of current approach:

    public List<Integer> largestValues(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            traverse(0, root, list);
            return list;
        }
        
        private void traverse(int level, TreeNode node, List<Integer> list) {
            if (node == null) {
                return;
            }
            
            if (list.size() <= level) {
                list.add(node.val);
            } else if (list.get(level) < node.val) {
                list.set(level, node.val);
            }
            
            traverse(level + 1, node.left, list);
            traverse(level + 1, node.right, list);
        }
    

Log in to reply
 

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