Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Step-By-Step Directions From a Binary Tree Node to Another

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2096" 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 are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: 'L' means to go from a node to its left child node. 'R' means to go from a node to its right child node. 'U' means to go from a node to its parent node. Return the step-by-step directions of the shortest path from node s to node t. Example 1: Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. Example 2: Input: root = [2,1], startValue = 2, destValue = 1 Output: "L" Explanation: The shortest path is: 2 → 1. Constraints: The number of nodes in the tree is n. 2 <= n <= 105 1 <= Node.val <= n All the values in the tree are unique. 1 <= startValue, destValue <= n startValue != destValue

Explanation

Here's the breakdown of the solution:

  • Find Paths to Nodes: Perform Depth-First Search (DFS) to find the paths from the root to both the startValue and destValue nodes. Store these paths as strings of 'L' and 'R' characters.
  • Locate Lowest Common Ancestor (LCA): Iterate through the paths from the root to the start and destination nodes simultaneously. Find the point where the paths diverge. This divergence point indicates the paths from the LCA to each node.
  • Construct the Final Path: The path from startValue to destValue consists of two parts: moving up from startValue to the LCA (represented by 'U' characters), and then moving down from the LCA to destValue (using the path string obtained earlier).

  • Time & Space Complexity: Time Complexity: O(N), where N is the number of nodes. Space Complexity: O(N) for storing the paths and recursion stack.

Code

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

def getDirections(root, startValue, destValue):
    """
    Finds the shortest path from startValue to destValue in a binary tree.

    Args:
        root: The root of the binary tree.
        startValue: The value of the start node.
        destValue: The value of the destination node.

    Returns:
        A string representing the directions (L, R, U) of the shortest path.
    """

    def find_path(node, target, path):
        """
        Performs DFS to find the path from the root to the target node.

        Args:
            node: The current node being visited.
            target: The target value to find.
            path: The path string being built.

        Returns:
            The path string if the target is found, otherwise None.
        """
        if not node:
            return None

        if node.val == target:
            return path

        left_path = find_path(node.left, target, path + "L")
        if left_path:
            return left_path

        right_path = find_path(node.right, target, path + "R")
        if right_path:
            return right_path

        return None

    start_path = find_path(root, startValue, "")
    dest_path = find_path(root, destValue, "")

    i = 0
    while i < min(len(start_path), len(dest_path)) and start_path[i] == dest_path[i]:
        i += 1

    up_moves = "U" * (len(start_path) - i)
    down_moves = dest_path[i:]

    return up_moves + down_moves

More from this blog

C

Chatmagic blog

2894 posts