Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Construct String from Binary Tree in Python
Constructing a string representation of a binary tree using parentheses helps visualize tree structure. This approach uses preorder traversal where null nodes are represented by empty parenthesis pairs (), and unnecessary empty pairs are omitted to maintain one-to-one mapping.
Problem Overview
Given a binary tree, we need to construct a string with parentheses and integers using preorder traversal. The rules are ?
- Each node's value is followed by its children in parentheses
- Null nodes are represented as empty parentheses
() - Omit empty parentheses that don't affect the tree structure
- If a node has no children, no parentheses are added
Algorithm Steps
The algorithm follows these steps ?
- If node is null, return empty string
- If node is a leaf (no children), return just the node value
- Add left child in parentheses (or empty parentheses if null)
- Add right child in parentheses only if it exists
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(temp, data):
queue = [temp]
while queue:
current = queue.pop(0)
if not current.left:
if data is not None:
current.left = TreeNode(data)
else:
current.left = TreeNode(0)
break
else:
queue.append(current.left)
if not current.right:
if data is not None:
current.right = TreeNode(data)
else:
current.right = TreeNode(0)
break
else:
queue.append(current.right)
def make_tree(elements):
if not elements:
return None
root = TreeNode(elements[0])
for element in elements[1:]:
insert(root, element)
return root
class Solution:
def tree2str(self, root):
def helper(node):
if node is None or node.data == 0:
return ''
# Leaf node - no parentheses needed
if node.left is None and node.right is None:
return str(node.data)
result = str(node.data)
# Add left child
if node.left is not None:
result += '(' + helper(node.left) + ')'
else:
# Only add empty parentheses if right child exists
if node.right is not None:
result += '()'
# Add right child
if node.right is not None:
result += '(' + helper(node.right) + ')'
return result
return helper(root)
# Create and test the solution
solution = Solution()
root = make_tree([5, 6, 7, None, 8])
result = solution.tree2str(root)
print(result)
5(6()(8))(7)
How It Works
The algorithm uses a recursive helper function that ?
- Base case: Returns empty string for null nodes
- Leaf case: Returns just the node value without parentheses
- Left child: Always processed, empty parentheses added if null and right child exists
- Right child: Only added if it exists (no empty parentheses for missing right child)
Key Points
- Empty parentheses
()are only added for null left child when right child exists - Missing right children don't require empty parentheses
- Leaf nodes don't need any parentheses
- The traversal follows preorder: root, left, right
Conclusion
This algorithm efficiently converts a binary tree to its string representation using preorder traversal. The key insight is knowing when to omit empty parentheses while preserving the tree's structure for reconstruction.
