606. Construct String from Binary Tree
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to convert a binary tree into a string representation. The format follows a preorder traversal, where each node is represented by its value, and its children are enclosed in parentheses. The main challenge lies in the specific rules for omitting parentheses to keep the string concise while preserving the tree's structure. The key rules are:
Solution
Construct String from Binary Tree in Python
# 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:
# Base case: if the node is null, return an empty string.
if not root:
return ""
# Start with the current node's value.
s = str(root.val)
# If the current node is a leaf, no parentheses are needed.
if not root.left and not root.right:
return s
# Always add parentheses for the left child's subtree.
# If root.left is None, self.tree2str(root.left) will be "", resulting in "()".
s += f"({self.tree2str(root.left)})"
# Only add parentheses for the right child if it exists.
if root.right:
s += f"({self.tree2str(root.right)})"
return s
Construct String from Binary Tree in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public String tree2str(TreeNode root) {
// Base case: if the node is null, return an empty string.
if (root == null) {
return "";
}
// Start with the current node's value.
String s = Integer.toString(root.val);
// If the current node is a leaf, no parentheses are needed.
if (root.left == null && root.right == null) {
return s;
}
// Always add parentheses for the left child's subtree.
// If root.left is null, tree2str(root.left) will be "", resulting in "()".
s += "(" + tree2str(root.left) + ")";
// Only add parentheses for the right child if it exists.
if (root.right != null) {
s += "(" + tree2str(root.right) + ")";
}
return s;
}
}
Construct String from Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* root) {
// Base case: if the node is null, return an empty string.
if (!root) {
return "";
}
// Start with the current node's value.
string s = std::to_string(root->val);
// If the current node is a leaf, no parentheses are needed.
if (!root->left && !root->right) {
return s;
}
// Always add parentheses for the left child's subtree.
// If root->left is null, this becomes "()".
s += "(" + tree2str(root->left) + ")";
// Only add parentheses for the right child if it exists.
if (root->right) {
s += "(" + tree2str(root->right) + ")";
}
return s;
}
};
Construct String from Binary Tree in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function tree2str(root: TreeNode | null): string {
// Base case: if the node is null, return an empty string.
if (!root) {
return "";
}
// Start with the current node's value.
let s = `${root.val}`;
// If the current node is a leaf, no parentheses are needed.
if (!root.left && !root.right) {
return s;
}
// Always add parentheses for the left child's subtree.
// If root.left is null, tree2str(root.left) will be "", resulting in "()".
s += `(${tree2str(root.left)})`;
// Only add parentheses for the right child if it exists.
if (root.right) {
s += `(${tree2str(root.right)})`;
}
return s;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.