-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path98-validate-binary-search-tree.js
More file actions
38 lines (34 loc) · 993 Bytes
/
98-validate-binary-search-tree.js
File metadata and controls
38 lines (34 loc) · 993 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
37
38
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
function checkTree(node) {
if(!node) {
return [true, null, null]
}
if(!node.left && !node.right) {
return [true, node.val, node.val]
}
const [lValid, lMin, lMax] = checkTree(node.left)
if(!lValid) return [false, 0, 0]
const [rValid, rMin, rMax] = checkTree(node.right)
if(!rValid) return [false, 0, 0]
if((lMax && lMax>=node.val) || (rMin && rMin<=node.val)) {
return [false, node.val, node.val]
}
const newMin = lMin===null ? node.val : lMin
const newMax = rMax===null ? node.val : rMax
return [true, newMin, newMax]
}
const res = checkTree(root)
return res[0]
};