Solving Leetcode Interviews in Seconds with AI: Delete Nodes And Return Forest
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1110" 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, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000.
Explanation
Here's a solution that addresses the problem efficiently:
High-Level Approach:
- Perform a post-order traversal of the binary tree. This allows us to process the children before the parent.
- During the traversal, check if the current node's value is in the
to_deleteset. - If it is, remove the node and add its non-null children to the result list as new roots. If it isn't, check if the parent needs to be updated.
Complexity:
- Runtime Complexity: O(N), where N is the number of nodes in the tree. We visit each node once.
- Storage Complexity: O(H + D), where H is the height of the tree (for recursion stack) and D is the size of the
to_deleteset. In the worst case, H can be N (skewed tree).
Code
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[Optional[TreeNode]]:
result = []
to_delete_set = set(to_delete)
def helper(node: Optional[TreeNode], is_root: bool) -> Optional[TreeNode]:
if not node:
return None
# Process children first (post-order)
node.left = helper(node.left, node.val in to_delete_set)
node.right = helper(node.right, node.val in to_delete_set)
if node.val in to_delete_set:
if node.left:
result.append(node.left)
if node.right:
result.append(node.right)
return None # Remove the node
if is_root:
result.append(node)
return node
helper(root, True) # Initially, the root is the root of a tree
return result