Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Construct String from Binary Tree

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "606" 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 node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines: Node Representation: Each node in the tree should be represented by its integer value. Parentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically: If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node's value. If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child. Omitting Empty Parentheses: Any empty parentheses pairs (i.e., ()) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained. In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately. Example 1: Input: root = [1,2,3,4] Output: "1(2(4))(3)" Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)". Example 2: Input: root = [1,2,3,null,4] Output: "1(2()(4))(3)" Explanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child. Constraints: The number of nodes in the tree is in the range [1, 104]. -1000 <= Node.val <= 1000

Explanation

Here's the breakdown of the solution:

  • Preorder Traversal: The solution uses a preorder traversal (root, left, right) to generate the string representation.
  • Conditional Parentheses: It adds parentheses around the left and right child values based on whether the children exist. Empty parentheses () are included only when a right child exists but a left child does not.
  • String Building: A string builder (in this case, Python's string concatenation) is used to efficiently construct the final string.

  • Runtime Complexity: O(N), where N is the number of nodes in the tree.

  • Storage Complexity: O(H), where H is the height of the tree, due to the recursive call stack. In the worst case (skewed tree), H = N, so the space complexity can be O(N).

Code

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

def tree2str(root: TreeNode) -> str:
    """
    Converts a binary tree to a string representation using preorder traversal.
    """

    if not root:
        return ""

    result = str(root.val)

    if root.left:
        result += "(" + tree2str(root.left) + ")"
    elif root.right:
        result += "()"  # Add empty parentheses if only right child exists

    if root.right:
        result += "(" + tree2str(root.right) + ")"

    return result

More from this blog

C

Chatmagic blog

2894 posts