1class TreeNode {
2 constructor(
3 public val: number,
4 public left: TreeNode | null = null,
5 public right: TreeNode | null = null,
6 ) {}
7}
8
9function insert(root: TreeNode | null, val: number): TreeNode {
10 if (!root) return new TreeNode(val); // Empty spot — insert here
11 if (val < root.val) {
12 root.left = insert(root.left, val); // Go left if smaller
13 } else if (val > root.val) {
14 root.right = insert(root.right, val); // Go right if larger
15 }
16 return root;
17}
18
19function inorder(root: TreeNode | null): number[] {
20 if (!root) return [];
21 return [...inorder(root.left), root.val, ...inorder(root.right)];
22}
23
24// Build BST: 5 → 3 → 7 → 1 → 4 → 6
25let root = null as TreeNode | null;
26for (const v of [5, 3, 7, 1, 4, 6]) root = insert(root, v);
27inorder(root); // → [1, 3, 4, 5, 6, 7]