Construct a Binary Tree from a String with Bracket Representation
⬅ Previous TopicBoundary Traversal of a Binary Tree
Next Topic ⮕Convert a Binary Tree into a Doubly Linked List
Next Topic ⮕Convert a Binary Tree into a Doubly Linked List
Visualization Player
Solution
Algorithm Steps
Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def str2tree(s: str):
if not s:
return None
def helper(i):
# Parse number (handle negative numbers)
sign = 1
if s[i] == '-':
sign = -1
i += 1
num = 0
while i < len(s) and s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
node = TreeNode(sign * num)
# Parse left subtree if '(' found
if i < len(s) and s[i] == '(':
i += 1 # skip '('
node.left, i = helper(i)
i += 1 # skip ')'
# Parse right subtree if '(' found
if i < len(s) and s[i] == '(':
i += 1 # skip '('
node.right, i = helper(i)
i += 1 # skip ')'
return node, i
root, _ = helper(0)
return root
# Example usage:
if __name__ == '__main__':
s = "4(2(3)(1))(6(5))"
root = str2tree(s)
# A function to print the tree can be added for verification
print(root.val)