Simple Java AC Solution


  • 0
    J

    Typical Level Order Traversal

    	public List<Double> averageOfLevels(TreeNode root) {
    		List<Double> ret = new LinkedList<Double>();
    		if (root == null) {
    			return ret;
    		}
    		Queue<TreeNode> q = new LinkedList<TreeNode>();
    		q.offer(root);
    		while (!q.isEmpty()) {
    			int sz = q.size();
    			double sum = 0.0;
    			for (int i = 0; i < sz; i++) {
    				TreeNode node = q.poll();
    				sum += node.val;
    				if (node.left != null) {
    					q.offer(node.left);
    				}
    				if (node.right != null) {
    					q.offer(node.right);
    				}
    			}
    			ret.add(sum / sz);
    		}
    		return ret;
    	}
    
    

Log in to reply
 

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