The problem “606. Construct String from Binary Tree” on LeetCode is defined as follows:
You need to construct a string from a binary tree with the preorder traversal way. The preorder traversal follows visit node -> traverse left -> traverse right.
You might use parentheses to indicate subtrees. Empty parentheses ()
are unnecessary, and you should omit them when you understand that it doesn’t affect the tree’s structure.
Example:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: "1(2(4))(3)"
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4
Output: "1(2()(4))(3)"
What type of data will be present in the tree nodes? The tree nodes will contain integer values.
Can the tree be empty? Yes, the tree can be empty, in which case the output should be an empty string.
Are there any constraints on the size of the tree? There’s no explicit size constraint provided, but typically, we’ll assume it fits in memory for solving typical interview-level problems.
Recursive Traversal: We’ll perform a preorder traversal (visit the root, traverse the left subtree, and then traverse the right subtree).
String Construction:
()
for the left subtree.# 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: TreeNode) -> str:
# Helper function to recurse through the tree and build the string
def dfs(node: TreeNode) -> str:
if not node:
return ""
# Convert the node value to string
result = str(node.val)
# Process the left child
if node.left or node.right: # if there's a right child we need parentheses
result += f"({dfs(node.left)})"
# Process the right child
if node.right:
result += f"({dfs(node.right)})"
return result
return dfs(root)
# Example Usage:
# Construct the tree [1,2,3,null,4]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(4)
sol = Solution()
print(sol.tree2str(root)) # Output: "1(2()(4))(3)"
The time complexity for this solution is (O(n)), where (n) is the number of nodes in the tree. Each node is visited exactly once in a preorder traversal, and building the string for each node requires constant time operations for appending strings.
The space complexity is (O(h)) where (h) is the height of the tree. This accounts for the recursive stack space used during the preorder traversal.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?