Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #536: Construct Binary Tree from String

In this guide, we solve Leetcode #536 Construct Binary Tree from String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Stack, Tree, Depth-First Search, String, Binary Tree

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

Input: s = "4(2(3)(1))(6(5))" Output: [4,2,6,3,1,5]

Python Solution

# 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 str2tree(self, s: str) -> TreeNode: def dfs(s): if not s: return None p = s.find('(') if p == -1: return TreeNode(int(s)) root = TreeNode(int(s[:p])) start = p cnt = 0 for i in range(p, len(s)): if s[i] == '(': cnt += 1 elif s[i] == ')': cnt -= 1 if cnt == 0: if start == p: root.left = dfs(s[start + 1 : i]) start = i + 1 else: root.right = dfs(s[start + 1 : i]) return root return dfs(s)

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy