LeetCode 637. Average of Levels in Binary Tree

LeetCode 637. Average of Levels in Binary Tree

Question: Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.

Screenshot from 2022-09-14 19-30-42.png


To solve this question you need to create a queue to temporarily store the nodes that are present in a particular level of a tree. we are using a queue so that we can take advantage of the FIFO operation i.e the first node in the queue will also be the first one to leave the Queue when performing a remove operation.

After creating the queue you will need to add the root into the queue and then we perform a while loop that will run as long as the queue is not empty. In the while loop, you will need to create 3 variables; a variable to store the size of the queue, the sum of the values of the Nodes present in a level and lastly the variable to store the size in another variable because as we loop over the queue we want to decrease it's size and then check if each node has left or right node. If a Node(parent node) has a child node on either the left or right we want to push it into the queue while we remove the parent from the queue. we then add the parent/parents(a scenario whereby 2 child nodes are parents to another node) to together and divide it by the count a. lastly, we will store it in the result and continue the operation until the queue is empty which means we have transverse overall child node.

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList();
        if(root == null)return result;

        Queue<TreeNode> q = new LinkedList();
            int size = q.size();
            double sum = 0,count = size;

            while(size-- >0){
                TreeNode node = q.poll();
                if(node.left !=null)q.offer(node.left);
                if(node.right !=null)q.offer(node.right);
                sum +=node.val;
        return result;

#personalJournal #LearningByExplaining

Did you find this article valuable?

Support Sylvester Amaechi by becoming a sponsor. Any amount is appreciated!