-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
54 lines (42 loc) · 920 Bytes
/
solution.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
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* @lc app=leetcode id=98 lang=javascript
*
* [98] Validate Binary Search Tree
*/
type MaybeTreeNode = TreeNode | null;
type TreeNode = {
val: number;
left: MaybeTreeNode;
right: MaybeTreeNode;
};
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
const isValidBST = (root: MaybeTreeNode): boolean => {
// * ['56 ms', '96.7 %', '37.2 MB', '97.44 %']
const stack: TreeNode[] = [];
let lastVal = -Infinity;
let head = root;
while (head !== null || stack.length > 0) {
while (head !== null) {
stack.push(head);
head = head.left;
}
head = stack.pop()!;
if (lastVal >= head.val) return false;
lastVal = head.val;
head = head.right;
}
return true;
};
// @lc code=end
export { isValidBST };