2020_9_12 每日一题 二叉树的层平均值

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。

示例 1:

输入:
3
/ \
9 20
/ \
15 7
输出:[3, 14.5, 11] 解释: 第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。

提示:

节点值的范围在32位有符号整数范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2020_9_6 每日一题 二叉树的层次遍历 II可以采用完全一样的思路。这次先实现一个广度优先搜索的:

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        //前段时间是不是有个求和的这玩意来着
        //完全一样的思路 treewalk或者广度优先搜索
        //这次先用广度优先搜索
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Double> ans = new ArrayList<>();
        queue.add(root);

        while(!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for(int i = 0; i < size; ++i) {
                TreeNode cur = queue.removeFirst();
                sum += cur.val;
                if(cur.left != null)
                	queue.add(cur.left);
                if(cur.right != null)
                	queue.add(cur.right);
            }
            ans.add(sum / size);
        }
        
        return ans;
    }
}

每一层分别处理可以不用记录当前层级。

然后实现一个treewalk的,这样需要再处理每一个节点的时候记录当前层级(说是treewalk其实和dfs是一个意思):

class Solution {
	
	private void dfs(TreeNode cur, int level, ArrayList<Integer> count, ArrayList<Double> sum) {
		if(cur == null)
			return;
		if(count.size() < level + 1) {
			count.add(1);
			sum.add((double)cur.val);
		} else {
			count.set(level, count.get(level) + 1);
			sum.set(level, sum.get(level) + cur.val);
		}
		
		dfs(cur.left, level + 1, count, sum);
		dfs(cur.right, level + 1, count, sum);
	}
	
    public List<Double> averageOfLevels(TreeNode root) {
        ArrayList<Integer> count = new ArrayList<Integer>();
        ArrayList<Double> sum = new ArrayList<Double>();
        dfs(root, 0, count, sum);
        
        List<Double> ans = new ArrayList<Double>();
        for(int i = 0; i < count.size(); ++i) {
        	ans.add(sum.get(i) / count.get(i));
        }
        
        return ans;
    }
}

居然还快了1ms
另外周末不是困难题,爷青结 是今天有比赛吗

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值