leetcode 637. Average of Levels in Binary Tree

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node's value is in the range of 32-bit signed integer.
简单题,用BFS,唯一注意是sum需要是long类型,不然会溢出。

package leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Average_of_Levels_in_Binary_Tree_637 {

	public List averageOfLevels(TreeNode root) {
		List list=new ArrayList();
		if(root==null){
			return list;
		}
		Queue queue=new LinkedList();
		queue.offer(root);
		while(!queue.isEmpty()){
			int size=queue.size();
			long sum=0;
			for(int i=0;i list=a.averageOfLevels(root);
		for(Double d:list){
			System.out.print(d+" ");
		}
	}

}
大神DFS解法见: https://leetcode.com/problems/average-of-levels-in-binary-tree/#/solution

其中 i 代表层数。sum这个list中,sum.get(0)代表0层数的和。count这个list中,count.get(0)代表0层数的node个数。

public class Solution {
    public List < Double > averageOfLevels(TreeNode root) {
        List < Integer > count = new ArrayList < > ();
        List < Double > res = new ArrayList < > ();
        average(root, 0, res, count);
        for (int i = 0; i < res.size(); i++)
            res.set(i, res.get(i) / count.get(i));
        return res;
    }
    public void average(TreeNode t, int i, List < Double > sum, List < Integer > count) {
        if (t == null)
            return;
        if (i < sum.size()) {
            sum.set(i, sum.get(i) + t.val);
            count.set(i, count.get(i) + 1);
        } else {
            sum.add(1.0 * t.val);
            count.add(1);
        }
        average(t.left, i + 1, sum, count);
        average(t.right, i + 1, sum, count);
    }
}

你可能感兴趣的:(leetcode 637. Average of Levels in Binary Tree)