LeetCode Algorithmic Question - Average of Levels in Binary Tree (Java Implementation)

Keywords: Eclipse JDK Java

This is the 277th update of Yueyue Book, 293 original works.

01 Look at the topic and prepare

Today, we introduce LeetCode algorithm question 145 at the Easy level (rank 637). Given a non-empty binary tree, the average value of the sum of node values at each level is returned as an array. For example:

    3
   / \
  9  20
     / \
    15  7

Output: [3, 14.5, 11]

Explanation: The average value of nodes on the first layer is 3, the average value of nodes on the second layer is 14.5, and the average value of nodes on the third layer is 11. So it returns [3, 14.5, 11].

Note: The range of node values is within 32-bit signed integers.

The development tool used in this problem solving is eclipse. The version used by jdk is 1.8. The environment is win7 64 bit system. It is written and tested in Java language.

02 First Solution

Use breadth first algorithm (BFS). When traversing nodes, we use two layers of loops, the number of outer control layers, and the sum of the node values of each layer is calculated by the inner layer. After the inner layer loops, we calculate the average value in the outer loop and add the average value to the array. One thing to note is that when calculating the sum of node values, you need to use long type to avoid overflow.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<Double>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // The number of control layers, the size of which is the number of nodes contained in the current layer            
            int size = queue.size();
            int count = 0;
            // Use long type to avoid overflow            
            long sum = 0;
            // Processing node values at each level
            while (size > 0) {
                TreeNode temp = queue.poll();
                count++;
                if (temp != null) {
                    sum += temp.val;
                }
                if (temp != null && temp.left != null) {
                    queue.offer(temp.left);
                }
                if (temp != null && temp.right != null) {
                    queue.offer(temp.right);
                }
                size--;
            }
            // Calculate the average and add it to the array
            list.add(sum*1.0d/count);
        }
        return list;
    }
}


03 Second Solution

Depth first algorithm (DFS) is used. When using depth-first algorithm, it is necessary to calculate the sum of the node values of each layer separately. At the same time, the number of nodes in each layer should be stored. With the help of recursive algorithm, after obtaining two sets of data, the average value of each layer can be calculated by a cycle.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        // The sum of node values for each layer
        List<Double> list = new ArrayList<Double>();
        if (root == null) {
            return list;
        }
        // Number of nodes stored in each layer
        List<Integer> count = new ArrayList<Integer>();
        dfs(0, root, list, count);
        // Calculate average
        for (int i=0; i<list.size(); i++) {
            list.set(i, list.get(i)/count.get(i));
        }
        return list;
    }

    public void dfs(int deep, TreeNode root, List<Double> list, List<Integer> count) {
        if (root == null) {
            return ;
        }
        // Determine if it's still in the current layer
        if (deep < list.size()) {
            list.set(deep, list.get(deep)+root.val);
            count.set(deep, count.get(deep)+1);
        } else {
            // New layer
            list.add(1.0*root.val);
            count.add(1);
        }
        // Recursively call the remaining nodes
        dfs(deep+1, root.left, list, count);
        dfs(deep+1, root.right, list, count);
    }
}


04 summary

This problem is essentially a study of the BFS and DFS algorithms of binary tree. On the basis of traversing nodes, the data of nodes are processed hierarchically.

Algorithms topic has been more than four months. Algorithms Article 145 + articles, public dialog box replies to any key words in [Data Structure and Algorithms], [Algorithms], [Data Structure], to obtain a collection of articles.

Above is the whole content, if you have any good solution ideas, suggestions or other issues, you can leave a message below to exchange, praise, message, forwarding is my greatest return and support!

Posted by goldlikesnow on Thu, 14 Mar 2019 22:18:26 -0700