Java BFS solution


  • 0
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> retList = new ArrayList();
            Queue<TreeNode> q = new LinkedList();
            if(root == null) return retList;
            q.add(root);
            while(!q.isEmpty()) {
                int level = q.size();
                int max = Integer.MIN_VALUE;
                for(int i = 0; i < level; ++i) {
                    TreeNode curr = q.remove();
                    max = Math.max(max, curr.val);
                    if(curr.left != null) q.add(curr.left);
                    if(curr.right != null) q.add(curr.right);
                }
                retList.add(max);
            }
            return retList;
        }
    }
    

Log in to reply
 

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