1
var tree2str = function (root) {2
// Step 1: Base case - if the root is null, return an empty string3
if (root === null) return "";5
// Step 2: Start with the value of the current node as the result string6
let result = root.val.toString();8
// Step 3: Recursively process the left and right subtrees9
let leftSubtree = tree2str(root.left);10
let rightSubtree = tree2str(root.right);12
// Step 4: Check conditions to determine the final result13
if (leftSubtree === "" && rightSubtree === "") {14
// Both left and right subtrees are empty, return the current result17
if (leftSubtree === "") {18
// Left subtree is empty, include empty parentheses for it and the right subtree19
return result + "()" + "(" + rightSubtree + ")";21
if (rightSubtree === "") {22
// Right subtree is empty, include the left subtree23
return result + "(" + leftSubtree + ")";26
// Both left and right subtrees are non-empty, include both in the result27
return result + "(" + leftSubtree + ")" + "(" + rightSubtree + ")";