leetcode637. 二叉树的层平均值

1.题目描述:

给定一个非空二叉树的根节点root,以数组的形式返回每一层节点的平均值。与实际答案相差10-5以内的答案可以被接受。

leetcode637. 二叉树的层平均值_第1张图片

2.BFS层序遍历:

看完题目毫不犹豫选择广度层序遍历,代码很容易写。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List averageOfLevels(TreeNode root) {
        if (root == null) return null;
        List list = new ArrayList<>();
        Queue queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode temp = queue.poll();
                sum += temp.val;
                if (temp.left != null) queue.add(temp.left);
                if (temp.right != null) queue.add(temp.right);
            }
            list.add(sum / size);           
        }
        return list;
    }
}

3.DFS深度优先搜索遍历:

class Solution {
    public List averageOfLevels(TreeNode root) {
        List counts = new ArrayList();//用来维护每一层节点的数量
        List sums = new ArrayList();//用来维护每一层节点的平均值
        dfs(root, 0, counts, sums);
        List averages = new ArrayList();
        int size = sums.size();
        for (int i = 0; i < size; i++) averages.add(sums.get(i) / counts.get(i));
        return averages;
    }

    public void dfs(TreeNode root, int level, List counts, List sums) {
        if (root == null) return;
        if (level < sums.size()) {
            sums.set(level, sums.get(level) + root.val);//更新节点的平均值
            counts.set(level, counts.get(level) + 1);//更新节点的数量
        } else {
            sums.add(1.0 * root.val);
            counts.add(1);
        }
        dfs(root.left, level + 1, counts, sums);
        dfs(root.right, level + 1, counts, sums);
    }
}

你可能感兴趣的:(树,算法,数据结构,java,树结构,leetcode)