-
Notifications
You must be signed in to change notification settings - Fork 0
/
isBst.js
77 lines (65 loc) · 1.44 KB
/
isBst.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
function Node(val){
this.value = val;
this.left = null;
this.right = null;
}
function BinarySearchTree(){
this.root = null;
}
BinarySearchTree.prototype.push = function(val){
var root = this.root;
if(!root){
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
}
else{
currentNode = currentNode.left;
}
}
else{
if(!currentNode.right){
currentNode.right = newNode;
break;
}
else{
currentNode = currentNode.right;
}
}
}
}
var bst = new BinarySearchTree();
bst.push(3);
bst.push(2);
bst.push(1);
bst.push(4);
bst.push(5);
bst.push(0);
bst.push(6);
bst.push(7);
console.log(bst.root.right)
function isValidBST(tree) {
if (!tree) {
throw new Error('invalid tree');
}
return isValidBSTRecursive(tree.root, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY);
}
function isValidBSTRecursive(node, min, max) {
// console.log("MIN: ", min, "MAX: ", max)
if (node) {
if (node.val < min || node.val > max) {
return false;
}
return isValidBSTRecursive(node.left, min, node.value) &&
isValidBSTRecursive(node.right, node.value, max);
}
return true;
}
console.log(isValidBST(bst));