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
|
var isValidBST = function (root) { return _isValidBST(root,-Infinity,Infinity)
function _isValidBST(root,lower,upper){ if(root === null) return true
if(root.val <= lower || root.val >= upper) return false
return _isValidBST(root.left,lower,root.val) && _isValidBST(root.right,root.val,upper) } };
var isValidBST = function (root) { let prev = -Infinity return _isValidBST(root)
function _isValidBST(root) { if (root === null) return true
if(!_isValidBST(root.left)) return false if(root.val <= prev) return false prev = root.val
return _isValidBST(root.right) } };
var isValidBST = function (root) { let stack = [] let prev = -Infinity let cur = root while(stack.length || cur !== null){ if(cur!== null){ stack.push(cur) cur = cur.left }else{ cur = stack.pop() if(cur.val <= prev) return false prev = cur.val cur = cur.right } } return true };
|