-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtree.ts
More file actions
36 lines (33 loc) · 723 Bytes
/
tree.ts
File metadata and controls
36 lines (33 loc) · 723 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export type Tree<T> = {
kind: "leaf";
} | {
kind: "node";
left: Tree<T>;
value: T;
right: Tree<T>;
};
export function createNode<T>(value: T): Tree<T> {
return {
kind: "node",
left: { kind: "leaf" },
value,
right: { kind: "leaf" }
};
}
function insert<T>(tree: Tree<T>, value: T): Tree<T> {
if (tree.kind === "leaf") {
return createNode(value);
} else if (value < tree.value) {
return {
...tree,
left: insert(tree.left, value)
};
} else if (value > tree.value) {
return {
...tree,
right: insert(tree.right, value)
};
} else {
return tree; // Value already exists in tree
}
}