Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
Example 1:
Input: root = [2,1,3] Output: true
Example 2:
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.
Constraints:
[1, 104].-231 <= Node.val <= 231 - 1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To check if a family tree of numbers follows the strict rule where every descendant on the left is smaller and every descendant on the right is larger, the brute force approach is to inspect every single person in the tree and check all of their relatives. We do this by exhaustively looking at every node and comparing it against every single one of its descendants to make sure no one is breaking the rule.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, value=0, left_node=None, right_node=None):
self.val = value
self.left = left_node
self.right = right_node
class Solution:
def collect_all_descendants(self, current_node, collected_values):
if current_node is None:
return
collected_values.append(current_node.val)
self.collect_all_descendants(current_node.left, collected_values)
self.collect_all_descendants(current_node.right, collected_values)
def is_valid_bst(self, root_node: TreeNode) -> bool:
if root_node is None:
return True
nodes_to_visit = [root_node]
# We must evaluate every single node in the tree against its entire descendant tree
while len(nodes_to_visit) > 0:
current_person = nodes_to_visit.pop(0)
left_descendant_values = []
self.collect_all_descendants(current_person.left, left_descendant_values)
# Every descendant on the left branch must be strictly smaller than the current root
for left_value in left_descendant_values:
if left_value >= current_person.val:
return False
right_descendant_values = []
self.collect_all_descendants(current_person.right, right_descendant_values)
# Every descendant on the right branch must be strictly larger than the current root
for right_value in right_descendant_values:
if right_value <= current_person.val:
return False
if current_person.left is not None:
nodes_to_visit.append(current_person.left)
if current_person.right is not None:
nodes_to_visit.append(current_person.right)
# If all nodes satisfy the BST constraints across all checks, the tree is valid
return TrueTo check if a tree is a valid binary search tree, the best approach is to walk through it while keeping track of the allowed range of values for every branch. As we move deeper into the tree, we narrow these boundary limits based on the decisions made at each turn to ensure no rule is broken.
Here's how the algorithm would work step-by-step:
class Solution:
def isValidBST(self, root_node) -> bool:
def validate_node(current_node, lower_bound, upper_bound):
if current_node is None:
return True
# Node value must respect boundaries to preserve the binary search tree invariant.
if (lower_bound is not None and current_node.val <= lower_bound) or (upper_bound is not None and current_node.val >= upper_bound):
return False
# Moving left restricts the upper limit because all descendants must be smaller.
if not validate_node(current_node.left, lower_bound, current_node.val):
return False
# Moving right restricts the lower limit because all descendants must be larger.
if not validate_node(current_node.right, current_node.val, upper_bound):
return False
return True
return validate_node(root_node, None, None)| Case | How to Handle |
|---|---|
| Null or empty root node | Return true immediately because an empty tree is vacuously a valid BST. |
| Single-node tree | Return true since a tree with only a root has no children to violate BST properties. |
| Duplicate values anywhere in the tree | Enforce strict inequality constraints where left child must be strictly less than and right child strictly greater than the parent. |
| Node values spanning extreme integer limits like Integer.MIN_VALUE or Integer.MAX_VALUE | Use 64-bit integer ranges or null pointer bounds to avoid boundary integer collisions. |
| Subtree values that violate ancestor constraints locally despite valid parent-child relationships | Propagate dynamic valid minimum and maximum boundaries down the recursive call stack. |
| Highly skewed binary tree resembling a linked list | Ensure the recursive approach handles deep stacks or utilize iterative traversals to prevent stack overflow. |
| Negative numbers and zero values | Treat negative numbers and zero just like any other integer by relying on relative comparison operators. |
| Extremely deep tree exceeding standard recursion depth limits | Convert the recursive validation to an iterative stack-based approach to avoid stack overflow exceptions. |