Java - O(n) Solution - BFS


  • 0
    B
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            
            List<Integer> ans = new ArrayList<Integer>();
            
            if(root == null) {
                return ans;
            }
            
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            
            queue.offer(root);
            
            int len = 0;
            int max = 0;
            
            while(!queue.isEmpty()) {
                
                len = queue.size();    
                max = Integer.MIN_VALUE;
                
                for(int i = 0; i< len; i++) {
                    
                    TreeNode polled = queue.poll();
                    
                    if(polled.val > max) {
                        max = polled.val;
                    }
                    
                    if(polled.left != null) {
                        queue.offer(polled.left);
                    }
                    
                    if(polled.right != null) {
                        queue.offer(polled.right);
                    }
                    
                }
                
                ans.add(max);
            }
            
            return ans;
            
        }
    }
    

Log in to reply
 

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