-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
41 lines (40 loc) · 1.04 KB
/
index.ts
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
37
38
39
40
41
import { TreeNode } from "../binary-tree-inorder-traversal/TreeNode.ts";
export default function isValidBST(root: TreeNode | null): boolean {
const signal: Signal = { aborted: false };
if (!root) return false;
let result = true;
let last: number | undefined;
inorder(
root,
(a) => {
if (signal.aborted) throw Error("aborted");
if (typeof last === "undefined") {
last = a;
} else {
if (a > last) {
last = a;
} else {
signal.aborted = true;
result = false;
}
}
},
signal,
);
return result;
}
interface Signal {
aborted: boolean;
}
function inorder(
root: TreeNode | null,
output: (a: number) => void,
signal?: Signal,
) {
if (signal?.aborted) return;
if (!root) return;
inorder(root.left, output, signal);
if (signal?.aborted) return;
output(root.val);
inorder(root.right, output, signal);
}