Construct String from Binary Tree

easy tree dfs string

Problem

Given the root of a binary tree, construct a preorder string of the form "val(left)(right)". Omit empty parenthesis pairs that don't affect the one-to-one mapping between the string and the tree — specifically, drop the empty right subtree's "()", but keep an empty left subtree's "()" whenever the right exists.

Inputroot = [1, 2, 3, 4]
Output"1(2(4))(3)"
The leaf 4 is the left child of 2; 2's right is empty so its "()" is dropped.

def tree2str(root):
    if not root:
        return ""
    s = str(root.val)
    if root.left or root.right:
        s += "(" + tree2str(root.left) + ")"
    if root.right:
        s += "(" + tree2str(root.right) + ")"
    return s
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;
}
class Solution {
    public String tree2str(TreeNode root) {
        if (root == null) return "";
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        if (root.left != null || root.right != null) sb.append("(").append(tree2str(root.left)).append(")");
        if (root.right != null) sb.append("(").append(tree2str(root.right)).append(")");
        return sb.toString();
    }
}
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;
}
Time: O(n) Space: O(h) recursion stack