Skip to main content
LeetCode 536, Medium. Topics: Stack, Tree, Depth-First Search, String, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure. You always start to construct the left child node of the parent first if it exists.

Examples

Example 1

Constraints

  • 0 <= s.length <= 3 * 10^4
  • s consists of digits, ’(’, ’)’, and ’-’ only.
  • All numbers in the tree have value at most than 2^30.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026