Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
Input: root = [2,1,3]
Output: true
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
To validate whether a binary tree is a binary search tree, we can use an in-order traversal. The idea is that for a binary search tree, an in-order traversal should yield values in a strictly increasing order.
Alternatively, we can use a recursive function to ensure that each node meets the BST properties by enclosing the valid range of values for each node based on its position in the tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isValidBST(root):
def inorder(node, arr):
if not node:
return
inorder(node.left, arr)
arr.append(node.val)
inorder(node.right, arr)
values = []
inorder(root, values)
for i in range(1, len(values)):
if values[i] <= values[i - 1]:
return false
return true
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isValidBST(root):
def validate(node, low=float('-inf'), high=float('inf')):
if not node:
return True
if not (low < node.val < high):
return False
return (validate(node.left, low, node.val) and
validate(node.right, node.val, high))
return validate(root)
Both methods efficiently determine whether the binary tree is a valid BST, and each has its own advantages in terms of implementation simplicity and space efficiency.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?