3. Given the following TypeScript code snippet, what is the in-order traversal output of the BST created from the array
[1, 2, 3]?
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number) {
this.val = val;
this.left = null;
this.right = null;
}
}
function sortedArrayToBST(nums: number[]): TreeNode | null {
if (!nums.length) return null;
const mid = Math.floor(nums.length / 2);
const root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums.slice(0, mid));
root.right = sortedArrayToBST(nums.slice(mid + 1));
return root;
}
function inorder(root: TreeNode | null, res: number[] = []): number[] {
if (root) {
inorder(root.left, res);
res.push(root.val);
inorder(root.right, res);
}
return res;
}
const bstRoot = sortedArrayToBST([1, 2, 3]);
console.log(inorder(bstRoot));