-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-118-isBinarySearchTree.js
87 lines (68 loc) · 1.98 KB
/
structy-118-isBinarySearchTree.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// https://structy.net/problems/premium/is-binary-search-tree
class Node {
constructor(val) {
// constructor(val) { y6m mjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
this.val = val;
this.left = null;
this.right = null;
}
}
// p: root of bi tree
// r: boolean
const isBinarySearchTree = (root) => {
const arr = explore(root);
for (let i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) return false;
}
return true;
};
// better explore
const explore = (root, arr) => {
if (!root) return;
explore(root.left, arr);
arr.push(root.val);
explore(root.right, arr);
};
// const explore = (root, arr = []) => {
// if (!root) return [];
// const left = explore(root.left, arr);
// const right = explore(root.right, arr);
// arr = arr.concat(left);
// arr.push(root.val);
// arr = arr.concat(right);
// return arr;
// };
// const isBinarySearchTree = (root) => {
// const stack = [root];
// while (stack.length > 0) {
// const current = stack.pop();
// current.left && current.left.val < current.val && stack.push(current.left)
// if (current.left && current.right) {
// if (current.left.val <= current.right.val) {
// stack.push(current.left);
// stack.push(current.right);
// // 122?./l-09+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-*umlk, ,;'l,;.'/]' current.right) {
// } else {
// return false;
// }
// }
// }
// return true;
// };
const a = new Node(12);
const b = new Node(5);
const c = new Node(18);
const d = new Node(3);
const e = new Node(9);
const f = new Node(19);
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
// 12
// / \
// 5 18
// / \ \
// 3 9 19
console.log(isBinarySearchTree(a)); // -> true