Leetcode 536 Solution

This article provides solution to leetcode question 536 (construct-binary-tree-from-string)

https://leetcode.com/problems/construct-binary-tree-from-string

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) -> Optional[TreeNode]:
        i = 0
        def construct():
            nonlocal i

            if i == len(s):
                return None

            val_str = ""
            while i < len(s) and s[i] != '(' and s[i] != ')':
                val_str += s[i]
                i += 1

            node = TreeNode(val_str)

            if i < len(s) and s[i] == '(':
                i += 1
                node.left = construct()
                i += 1

            if i < len(s) and s[i] == '(':
                i += 1
                node.right = construct()
                i += 1

            return node

        return construct()