Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Validate Binary Tree Nodes

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1361" 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

You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. Example 1: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] Output: true Example 2: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] Output: false Example 3: Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] Output: false Constraints: n == leftChild.length == rightChild.length 1 <= n <= 104 -1 <= leftChild[i], rightChild[i] <= n - 1

Explanation

Here's the breakdown of the solution:

  • Find the Root: Identify the potential root node(s) by determining nodes that are not children of any other node. If there isn't exactly one root, it's not a valid tree.
  • Validate Tree Structure: Perform a Breadth-First Search (BFS) or Depth-First Search (DFS) starting from the root. Check for cycles, disconnected components, and invalid node counts.
  • Ensure Full Coverage: Verify that all n nodes are reachable from the identified root. This confirms that there aren't any orphaned nodes.

  • Time and Space Complexity: O(n) time complexity, O(n) space complexity

Code

    def validateBinaryTreeNodes(n: int, leftChild: list[int], rightChild: list[int]) -> bool:
    """
    Checks if the given nodes form exactly one valid binary tree.
    """

    in_degree = [0] * n
    for i in range(n):
        if leftChild[i] != -1:
            in_degree[leftChild[i]] += 1
        if rightChild[i] != -1:
            in_degree[rightChild[i]] += 1

    roots = []
    for i in range(n):
        if in_degree[i] == 0:
            roots.append(i)

    if len(roots) != 1:
        return False

    root = roots[0]
    visited = [False] * n
    queue = [root]
    visited[root] = True
    count = 0

    while queue:
        node = queue.pop(0)
        count += 1

        left = leftChild[node]
        right = rightChild[node]

        if left != -1:
            if visited[left]:
                return False  # Cycle detected
            visited[left] = True
            queue.append(left)

        if right != -1:
            if visited[right]:
                return False  # Cycle detected
            visited[right] = True
            queue.append(right)

    return count == n  # Check if all nodes are reachable

More from this blog

C

Chatmagic blog

2894 posts