Zepruv › Coding problems

Construct String from Binary Tree

Medium · String, Tree, Depth-First Search, Binary Tree

Given the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:

Example 1

Input: root = [1,2,3,4]
Output: "1(2(4))(3)"

Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)".

Example 2

Input: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"

Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.

Constraints

Starter code (python)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def tree2str(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: str
        """
        

Related problems

Previous: Can Place Flowers · Next: Find Duplicate File in System · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.