449. Serialize and Deserialize BST

Design an algorithm to serialize and deserialize a binary search tree

The encoded string should be as compact as possible.


def serialize(self, root: Optional[TreeNode]):
    if root is None:
        return ""
    s = self.serialize(root.left) + "," +  self.serialize(root.right) + "," + str(root.val)
    return s
       

def deserialize(data: str):
    def helper(low, high):
        if not nodeVals:
            return None
        if low > nodeVals[-1] or high < nodeVals[-1]:
            return None
       
        val = nodeVals.pop()
        root = TreeNode(val)
        root.right = helper(val, high)
        root.left = helper(low, val)
        return root

    nodeVals = [int(x) for x in data.split(',') if x]
    return helper(-math.inf, math.inf)

Comments

Popular posts from this blog

347. Top K Frequent Elements

849. Maximize Distance to Closest Person

674. Longest Continuous Increasing Subsequence