Validate Binary Search Tree
2
/ \
1 3 1
/ \
2 3Last updated
2
/ \
1 3 1
/ \
2 3Last updated
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
cur = root
s= []
pre = None
while cur or s:
while cur:
s.append(cur)
cur = cur.left
cur = s.pop()
if pre and pre.val >= cur.val:
return False
pre = cur
cur = cur.right
return True
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode root, long min, long max){
if(root == null)
return true;
if(root.val >= max ||root.val <= min){
return false;
}
return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
}
}