BST or Inorder
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode curt, long min, long max) {
if (curt == null) return true;
if (curt.val <= min || curt.val >= max) return false;
return helper(curt.left, min, curt.val)
&& helper(curt.right, curt.val, max);
}def isValidBST(self, root: TreeNode) -> bool:
return self.helper(root, -sys.maxsize + 1, sys.maxsize)
def helper(self, curt, minv, maxv) :
if not curt:
return True
if curt.val <= minv or curt.val >= maxv:
return False
return self.helper(curt.left, minv, curt.val) and self.helper(curt.right, curt.val, maxv)Last updated