Construct String from Binary Tree
MediumStringTreeDepth-First SearchBinary Tree
Solution
import { TreeNode } from '@algorithm/lib';
export function tree2str(root: TreeNode | null): string {
if (root === null) {
return '';
}
if (root.left === null && root.right === null) {
return root.val.toString();
}
if (root.right === null) {
return `${root.val}(${tree2str(root.left)})`;
}
return `${root.val}(${tree2str(root.left)})(${tree2str(root.right)})`;
}