EZ understand Java BFS


  • 0
    M
        public List<Integer> largestValues(TreeNode root) {
            // do a level order traverse. 
            
            if (root == null) return new LinkedList<>();
            
            List<Integer> maxes = new LinkedList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            
            while (!queue.isEmpty()) {
                List<Integer> temp = new LinkedList<>();
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode tempNode = queue.poll();
                    temp.add(tempNode.val);
                    if (tempNode.left != null) queue.add(tempNode.left);
                    if (tempNode.right != null) queue.add(tempNode.right);
                }
                maxes.add(Collections.max(temp));
            }
            
            return maxes;
        }
    

Log in to reply
 

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