Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Average of Levels in Binary Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "637" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. Example 1: Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000] 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]. Example 2: Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000] Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1

Explanation

  • Level-Order Traversal: The core idea is to traverse the binary tree level by level. This is achieved using a queue-based Breadth-First Search (BFS) approach.
    • Calculate Averages: For each level, we sum the values of all nodes at that level and divide by the number of nodes to get the average.
    • Store Results: The average values calculated for each level are stored in a list, which is returned as the final result.
  • Runtime Complexity: O(N), where N is the number of nodes in the tree. Storage Complexity: O(W), where W is the maximum width of the tree (maximum number of nodes at any level). In the worst case (complete binary tree), W can be approximately N.

Code

    from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def averageOfLevels(root):
    """
    Calculates the average value of the nodes on each level of a binary tree.

    Args:
        root: The root node of the binary tree.

    Returns:
        A list of floats, where each float represents the average value of the nodes on a level.
    """

    if not root:
        return []

    result = []
    queue = deque([root])

    while queue:
        level_size = len(queue)
        level_sum = 0

        for _ in range(level_size):
            node = queue.popleft()
            level_sum += node.val

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        result.append(level_sum / level_size)

    return result

More from this blog

C

Chatmagic blog

2894 posts