Java,bfs, level order traversal,10ms,beat 87%


  • 0
    simple java bfs, idea is based  on level order traversal
    78 / 78 test cases passed.
    	Status: Accepted
    Runtime: 10 ms
    
    public List<Integer> largestValues(TreeNode root) {
             List<Integer> result = new ArrayList<>();
            if (root == null) 
            return result;
            
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            
            while (!queue.isEmpty()) {
                int size = queue.size();
                int max = Integer.MIN_VALUE;
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    max = Math.max(max, node.val);
                    if (node.left != null) queue.add(node.left);
                    if (node.right != null) queue.add(node.right);
                }
                result.add(max);
            }
            return result;
        }

Log in to reply
 

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