Construct String from Binary Tree

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

Construct a string from a binary tree using preorder with parentheses. Omit empty parentheses that don't affect the one-to-one mapping.

Solutions

# Python
def tree2str(root):
    if not root:
        return ''
    left = f'({tree2str(root.left)})' if root.left or root.right else ''
    right = f'({tree2str(root.right)})' if root.right else ''
    return str(root.val) + left + right
// C++
string tree2str(TreeNode* root) {
    if (!root) return "";
    string s = to_string(root->val);
    if (root->left || root->right) s += "(" + tree2str(root->left) + ")";
    if (root->right) s += "(" + tree2str(root->right) + ")";
    return s;
}
// Java
public String tree2str(TreeNode root) {
    if (root == null) return "";
    String s = String.valueOf(root.val);
    if (root.left != null || root.right != null) s += "(" + tree2str(root.left) + ")";
    if (root.right != null) s += "(" + tree2str(root.right) + ")";
    return s;
}
// JavaScript
function tree2str(root) {
    if (!root) return '';
    let s = String(root.val);
    if (root.left || root.right) s += '(' + tree2str(root.left) + ')';
    if (root.right) s += '(' + tree2str(root.right) + ')';
    return s;
}

Complexity

  • Time: O(n)
  • Space: O(n)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro