Construct String from Binary Tree — LeetCode 606 Python Solution
- Problem
- #606
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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: Node Representation: Each node in the tree should be represented by its integer value.
Example
- Input
- root = [1,2,3,4]
- Output
- "1(2(4))(3)"
- Explanation
- 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)".
Python 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 tree2str(self, root: Optional[TreeNode]) -> str:
def dfs(root):
if root is None:
return ''
if root.left is None and root.right is None:
return str(root.val)
if root.right is None:
return f'{root.val}({dfs(root.left)})'
return f'{root.val}({dfs(root.left)})({dfs(root.right)})'
return dfs(root)Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 606. Construct String from Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 606. Construct String from Binary Tree?
- LeetCode 606. Construct String from Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 606. Construct String from Binary Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 606. Construct String from Binary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 606. Construct String from Binary Tree cover?
- LeetCode 606. Construct String from Binary Tree is tagged Tree, Depth-First Search, String and Binary Tree on LeetCode.