⬅ Previous Topic
Boundary Traversal of a Binary TreeNext Topic ⮕
Convert a Binary Tree into a Doubly Linked List⬅ Previous Topic
Boundary Traversal of a Binary TreeNext Topic ⮕
Convert a Binary Tree into a Doubly Linked List4(2(3)(1))(6(5))
).(
, recursively construct the left subtree and skip the corresponding )
.(
follows, recursively construct the right subtree and skip its closing )
.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)
⬅ Previous Topic
Boundary Traversal of a Binary TreeNext Topic ⮕
Convert a Binary Tree into a Doubly Linked ListYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.