Construct String from Binary Tree LeetCode solution in JavaScript

1
var tree2str = function (root) {
2
// Step 1: Base case - if the root is null, return an empty string
3
if (root === null) return "";
4

5
// Step 2: Start with the value of the current node as the result string
6
let result = root.val.toString();
7

8
// Step 3: Recursively process the left and right subtrees
9
let leftSubtree = tree2str(root.left);
10
let rightSubtree = tree2str(root.right);
11

12
// Step 4: Check conditions to determine the final result
13
if (leftSubtree === "" && rightSubtree === "") {
14
// Both left and right subtrees are empty, return the current result
15
return result;
16
}
17
if (leftSubtree === "") {
18
// Left subtree is empty, include empty parentheses for it and the right subtree
19
return result + "()" + "(" + rightSubtree + ")";
20
}
21
if (rightSubtree === "") {
22
// Right subtree is empty, include the left subtree
23
return result + "(" + leftSubtree + ")";
24
}
25

26
// Both left and right subtrees are non-empty, include both in the result
27
return result + "(" + leftSubtree + ")" + "(" + rightSubtree + ")";
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0