Construct Binary Tree from String — LeetCode 536 Python Solution
MediumLeetCode PremiumStackTreeDepth-First SearchStringBinary Tree
- Problem
- #536
- Pattern
- Stack
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree.
Example
- Input
- s = "4(2(3)(1))(6(5))"
- Output
- [4,2,6,3,1,5]
Python solution
Python
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 536. Construct Binary Tree from String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 536. Construct Binary Tree from String?
- LeetCode 536. Construct Binary Tree from String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 536. Construct Binary Tree from String?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 536. Construct Binary Tree from String?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 536. Construct Binary Tree from String cover?
- LeetCode 536. Construct Binary Tree from String is tagged Stack, Tree, Depth-First Search, String and Binary Tree on LeetCode.
- Is LeetCode 536. Construct Binary Tree from String a premium problem?
- Yes. LeetCode 536. Construct Binary Tree from String is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.