Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Diameter of Binary Tree

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "543" 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 length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. Example 2: Input: root = [1,2] Output: 1 Constraints: The number of nodes in the tree is in the range [1, 104]. -100 <= Node.val <= 100

Explanation

  • The diameter of a tree can be found by considering each node as the highest point on a potential longest path.
    • For each node, the longest path through it is the sum of the heights of its left and right subtrees.
    • We can calculate the height of each node and the diameter simultaneously using recursion.
  • Runtime Complexity: O(N), Storage Complexity: O(H) where N is the number of nodes and H is the height of the tree. In the worst case (skewed tree) H can be equal to N, and in the best case (balanced tree) H is log(N).

Code

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

def diameterOfBinaryTree(root: TreeNode) -> int:
    """
    Calculates the diameter of a binary tree.

    Args:
        root: The root of the binary tree.

    Returns:
        The length of the diameter of the tree.
    """
    diameter = 0

    def height(node):
        nonlocal diameter
        if not node:
            return 0

        left_height = height(node.left)
        right_height = height(node.right)

        diameter = max(diameter, left_height + right_height)

        return 1 + max(left_height, right_height)

    height(root)
    return diameter

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Diameter of Binary Tree