naive java solution


  • 0
    D

    Two queue's to maintain levels

    public List<Double> averageOfLevels(TreeNode root) {
    
    		Queue<TreeNode> currentLevel = new LinkedList<>();
    		Queue<TreeNode> nextLevel = new LinkedList<>();
    
    		List<Double> ans = new ArrayList<>();
    
    		if (root == null)
    			return ans;
    
    		currentLevel.add(root);
    
    		
    		double temp = 0.0;
    		double tempCounter = 0;
    		
    		while (!currentLevel.isEmpty()) {
    
    			TreeNode node = currentLevel.poll();
    			temp += node.val;
    			tempCounter++;
    
    			if (node.left != null) {
    				nextLevel.offer(node.left);
    			}
    
    			if (node.right != null) {
    				nextLevel.offer(node.right);
    			}
    
    			if (currentLevel.isEmpty()) {
    				// switch q's
    				currentLevel = nextLevel;
    				nextLevel = new LinkedList<>();
    
    				ans.add(temp / tempCounter);
    
    				tempCounter = 0;
    				temp = 0.0;
    
    			}
    		}
    
    		return ans;
    
    	}
    

Log in to reply
 

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